【问题标题】:Mongoose - Schema with nested SchemaId arrayMongoose - 带有嵌套 SchemaId 数组的模式
【发布时间】:2022-01-20 01:01:19
【问题描述】:

我有一个创建餐厅的方法:

const { restaurant } = req;

        if (!restaurant || !Object.keys(restaurant).length) {
            return { msg: "Not enough data!", status: 500 };
        }
        const restaurantRecord = new Restaurants(restaurant);

        await restaurantRecord.save();

它具有以下架构:

const mongoose = require("mongoose");
const { Food } = require("./food");

const RestaurantsSchema = mongoose.Schema(
    {
        name: { type: String, index: true, unique: true, default: "Test queue" },
        menu: [{ type: mongoose.Schema.Types.ObjectId, ref: Food, index: true, default: [] }]
    },
    { collection: "restaurants" }
);

module.exports.Restaurants = mongoose.model("Restaurants", RestaurantsSchema);

它有一个 Food 模式数组:

const mongoose = require("mongoose");

const FoodSchema = mongoose.Schema(
    {
        name: { type: String, index: true, unique: true, default: "Some food" },
        price: { type: Number, index: true, default: 100 },
    },
    { collection: "food" }
);

module.exports.Food = mongoose.model("Food", FoodSchema);

当我尝试像这样在 Postman 中创建餐厅时:

{
    "restaurant":
    {
        "name": "Test restaurant",
        "menu":
        [
            {"name": "Test food"},
            {"name": "Test food 2"}
        ]
    }
}

我收到一个错误:

我该如何解决这个问题?我想它需要我创建 Food 对象或其他东西。

【问题讨论】:

    标签: javascript mongoose postman


    【解决方案1】:

    您必须添加 id 字段。

    还有很多关于这个错误的帖子here

    【讨论】:

      猜你喜欢
      • 2016-10-23
      • 2017-03-01
      • 2017-07-06
      • 2020-11-09
      • 2017-09-26
      • 1970-01-01
      • 2014-03-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多