I'm having a hard time trying to populate an array of sub-documents with MongooseJS. Could someone help?
Here is user.js:
var mongoose = require("mongoose");
var userSchema = new mongoose.Schema({
name: {
type: String
},
positions: [{
type: mongoose.Schema.ObjectId,
ref: 'position'
}]
});
userSchema.statics.getUserByID = function (id, callback){
return this.findOne({_id: id}).populate('positions').exec(callback);
};
var user = mongoose.model('user', userSchema);
module.exports = user;
And here is position.js
var mongoose = require("mongoose");
var positionSchema = new mongoose.Schema({
modifiedDate: {
type: Date
}
});
var position = mongoose.model('position', positionSchema);
module.exports = position;
The positions array of the user model isn't being populated when getUserByID is called. Am I missing something obvious here?
Here is what is currently saved in the users collection:
{
"__v": 1,
"_id": {
"$oid": "531f8ab89938130200433ef8"
},
"modifiedDate": {
"$date": "2014-03-11T22:14:43.174Z"
},
"name": "Josh",
"positions": [
{
"$oid": "531f8ad39938130200433efa"
}
]
}
And here is what's in the positions collection:
{
"modifiedDate": {
"$date": "2014-03-11T22:14:43.163Z"
},
"_id": {
"$oid": "531f8ad39938130200433efa"
},
"__v": 0
}
For reference I'm using "mongoose": "^3.8.8" in my package.json file.