简体   繁体   中英

Mongoose - Schema with nested SchemaId array

I have a method that creates restaurant:

const { restaurant } = req;

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

        await restaurantRecord.save();

It has the following schema:

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);

It has an array of Food schemas:

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);

When I try to create restourant in Postman like this:

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

i get an error: 在此处输入图像描述

How can I fix this? I guess it needs me to create Food object or something.

You have to add the id field.

There is many other post about this error seen here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM