I have a Mongoose schema with an array lists
of objects that consist of a reference to another collection and a nested array of numbers:
var Schema, exports, mongoose, schema; mongoose = require("mongoose"); Schema = mongoose.Schema; schema = new Schema({ name: { type: String, required: true, unique: true, trim: true }, lists: [ { list: { type: Schema.ObjectId, require: true, ref: "List" }, allocations: [ { type: Number, required: true } ] } ], createdAt: { type: Date, "default": Date.now }, updatedAt: { type: Date } }); exports = module.exports = mongoose.model("Portfolio", schema);
However, I cannot get populate
to work as expected without getting a TypeError: Cannot read property 'ref' of undefined
. I've tried populate('list')
and populate('lists list')
but I'm either not calling things correctly or my Schema isn't formed correctly. I don't have this problem if I simply reference the lists by themselves:
lists: [ { type: Schema.ObjectId, require: true, ref: "List" } ]
but I want to have the allocations array alongside each list. What do I need to do to get the behavior I want?
The ref option is what tells Mongoose which model to use during population, in our case the Story model. All _id s we store here must be document _id s from the Story model. Note: ObjectId , Number , String , and Buffer are valid for use as refs.
$push. The $push operator appends a specified value to an array. The $push operator has the form: { $push: { <field1>: <value1>, ... } } To specify a <field> in an embedded document or in an array, use dot notation.
I found the answer: populate('lists.list')
works. Thanks to this question: Mongoose populate within an object?
lists: [ { list: { type: Schema.ObjectId, require: true, ref: "List" }, allocations: [ { type: Number, required: true } ] } ],
=> Because it's an array of objects, you can do this -: Portfolio.populate('lists.list');
2.
lists: [ { type: Schema.ObjectId, require: true, ref: "List" } ]
=> Because it's an array, you just have to do this -: Portfolio.populate('lists');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With