Mongoose populate with array of objects containing ref
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?
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');