Why doesn't MongooseJS correctly populate my fields?
Don Nguyen <
don@...>
2012-05-16 01:41:36 GMT
I'm trying to adapt the example here
http://mongoosejs.com/docs/populate.html
I have removed stories and am trying to add a 'friends' field
instead. My code is as follows
var PersonSchema = new Schema({
name : String
, age : Number
, friends : [{ type: Schema.ObjectId, ref: 'Person' }]
});
var Person = mongoose.model('Person', PersonSchema);
var aaron = new Person({ name: 'Aaron', age: 100 });
var bill = new Person({ name: 'Bill', age: 97 });
aaron.save(function (err) {
if (err) throw err;
bill.save(function(err) {
if (err) throw err;
var charlie = new Person({ name: 'Charlie', age: 97, friends:
[aaron._id, bill._id] });
charlie.save(function(err) {
if (err) throw err;
Person
.findOne({name: 'Charlie'})
.populate('friends')
.run(function(err, friends) {
if (err) throw err
console.log('JSON for friends is: ', friends);
db.disconnect();
});
});
});
});
It prints out the following text
JSON for friends is: { name: 'Charlie',
age: 97,
_id: 4fb302beb7ec1f775e000003,
stories: [],
friends:
[ { name: 'Aaron',
age: 100,
_id: 4fb302beb7ec1f775e000001,
stories: [],
friends: [] },
{ name: 'Bill',
age: 97,
_id: 4fb302beb7ec1f775e000002,
stories: [],
friends: [] } ] }
In other words it is printing out the 'charlie' object. My desired
functionality is for MongooseJS to use ObjectIds in the friends field
and populate an array with the matching objects (aaron and bill). In
other words something more along the lines of
[ { name: 'Aaron',
age: 100,
_id: 4fb302beb7ec1f775e000001,
stories: [],
friends: [] },
{ name: 'Bill',
age: 97,
_id: 4fb302beb7ec1f775e000002,
stories: [],
friends: [] } ]
What am I doing wrong?