Home > Back-end >  How to populate object array in mongoose?
How to populate object array in mongoose?

Time:05-12

I wanted to populate 'item' in here and I'm getting the below error. It is an object array. This method worked for a normal array but gave an error for an object array. How to resolve it?

        // Get the reserved list
        const reservedDetails = await reserveInventory
            .findOne({ memberID: id })
            .select("itemsList")
            .populate({
                path: "item",
                model: inventoryItem,
            });

Error:

Cannot populate path `item` because it is not in your schema. Set the `strictPopulate` option to false to override.

reserveInventory Model:

const reserveInventorySchema = mongoose.Schema({
    memberID: {
        type: String,
        ref: "member",
        required: true,
    },
    itemsList: [
        {
            item: {
                type: String,
                ref: "inventoryItem",
            },
            quantity: {
                type: Number,
            },
        },
    ],
});

module.exports = mongoose.model("reserveInventory", reserveInventorySchema);

inventoryItem Model:

const inventoryItemSchema = mongoose.Schema(
    {
        name: {
            type: String,
            required: true,
        },
        quantity: {
            type: Number,
            required: true,
        },
        available: {
            type: Number,
            required: true,
        },
    },
    {
        timestamps: true,
    }
);

module.exports = mongoose.model("inventoryItem", inventoryItemSchema);

CodePudding user response:

you got it wrong here

// Get the reserved list
        const reservedDetails = await reserveInventory
            .findOne({ memberID: id })
            .select("itemsList")
            .populate({ path: "itemsList.item"});
  • Related