I am currently using mongoose v4.10.8 and am attempting to populate multiple arrays on a defined model.
TransportModel.js
//Transport model
'use strict';
const mongoose = require('mongoose');
const TransportSchema = new mongoose.Schema({
tag: {
type: String,
enum: ['X', 'Y'],
required: true,
unique: true
},
chairs: [{
type: mongoose.Schema.Types.ObjectId,
ref: "Chair"
}],
targets: [{
type: mongoose.Schema.Types.ObjectId,
ref: "Target"
}]
});
module.exports = mongoose.model('Transport', TransportSchema);
ChairModel.js
//Chair model
'use strict';
const mongoose = require('mongoose');
const ChairSchema = new mongoose.Schema({
product_name: {
type: String,
required: true,
unique: true
},
description: {
type: String,
unique: false,
required: false
}
});
module.exports = mongoose.model('Chair', ChairSchema);
TargetModel.js
//Target model
'use strict';
const mongoose = require('mongoose');
const TargetSchema = new mongoose.Schema({
target_name: {
type: String,
required: true,
unique: true
},
location: {
type: String,
required: true,
unique: false
},
description: {
type: String,
unique: false,
required: false
}
});
module.exports = mongoose.model('Target', TargetSchema);
After having the above configuration in place, I created one Chair document and one Target document.
Afterwards, I invoke the following logic on a route to get a single Transport document:
TransportModel.findOne({
tag: 'X'
})
.populate("chairs")
.populate("targets")
.exec(function(err, transport) {
if (err) {
console.error(err);
}
console.log('Transport: ', transport);
});
});
Below is the retrieved document:
{
"_id": "xxxx9999xxxx9999xxxx9999",
"tag": "X",
"__v": 1,
"chairs": [],
"targets": []
}
Thus, even though I queried the Chairs and Targets collections and I do have at least 1 document, the Transport document does not get populated.
Furthermore, I also tried the enhanced version of .populate(), but I keep getting empty arrays:
.populate({
path: "chairs",
model: "Chair"
})
.populate({
path: "targets",
model: "Target"
})
ChairandTargetdocuments to theTransportModeldocument?.populate(), I want thechairsandtargetsarrays of theTransportdocuments to be automatically populated with the entire available list ofChairandTargetdocuments from their respective collections.Chairdocument with aTransportModeldocument. The.populate()method will then add the associated documents automatically during queries. See the documentation: mongoosejs.com/docs/populate.html_idvalues associated withChairdocuments in thechairsarray, and afterwards.populate()simply brings the rest of the document properties from thechairscollection? That means that I still have to fire.find({})query and push the chairs to thechairsarray?TransportModeldocument, then yes. But if you want to associate all chairs and targets with a particularTransportModeldocument, population doesn't really seem to make sense, and you probably should run three different queries (one for each collection/model).