1

我想创建一个复杂的嵌套文档,它可以存储这样的值

category: {
  "fish": ["Sardines", "Goldfish"],
  "dogs": ["German Shepherd", "Dobberman"]
}

这是我尝试过的

export const CategorySchema = new mongoose.Schema(
  {
    category: {
      type: Map,
      of: [String],
    },
  },
  { timestamps: true }
);

我像这样(从控制台) 传递了数据,这就是传递的数据看起来像 什么都没有在数据库中创建的样子。也没有错误。

export default async (req, res) => {
  const { method } = req;
  switch (method) {
    case "GET":
      try {
        const categories = await Category.find({});
        res.json({ success: true, data: categories });
      } catch (error) {
        res.json({ success: false });
      }
      break;
    case "POST":
      try {
        let data = req.body;
        data = JSON.parse(data);
        const category = new Category(data);
        const doc = await category.save();
        console.log("Doc from Categories API", doc);
        res.json({ success: true, data: doc });
      } catch (error) {
        res.json({ success: false });
      }
      break;
    default:
      res.status(400).json({ success: false });
      break;
  }
};

有人可以给我建议吗?

4

0 回答 0