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 }, location: { type: [Number], index: '2d' } }); var position = mongoose.model('position', positionSchema); module.exports = position; The positions array of the user schema isn't being populated when getUserByID is called. Am I missing something obvious here?
EDIT
As per the answer below, I've changed my user schema to be:
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; I've also removed the location property from the position schema, in case there was something odd happening there.
Nothing I've tried seems to make any difference at all.
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.
I'm really stumped by this, any help would be appreciated.