我正在尝试调整此处的示例
http://mongoosejs.com/docs/populate.html
我已删除故事并尝试添加“朋友”字段。我的代码如下
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();
});
});
});
});
它打印出以下文本
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: [] } ] }
换句话说,它正在打印出 'charlie' 对象。我想要的功能是让 MongooseJS 在朋友字段中使用 ObjectIds 并用匹配的对象(aaron 和 bill)填充数组。换句话说,更像是
[ { name: 'Aaron',
age: 100,
_id: 4fb302beb7ec1f775e000001,
stories: [],
friends: [] },
{ name: 'Bill',
age: 97,
_id: 4fb302beb7ec1f775e000002,
stories: [],
friends: [] } ]
我究竟做错了什么?