2012-05-16 300 views
0

我试图适应这里的例子为什么MongooseJS不能正确填充我的字段?

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: [] } ] } 

换句话说,它是印刷出来的“查理”的对象。我期望的功能是让MongooseJS在friends字段中使用ObjectIds,并用匹配对象(aaron和bill)填充数组。换句话说,更多沿线的东西

[ { name: 'Aaron', 
     age: 100, 
     _id: 4fb302beb7ec1f775e000001, 
     stories: [], 
     friends: [] }, 
    { name: 'Bill', 
     age: 97, 
     _id: 4fb302beb7ec1f775e000002, 
     stories: [], 
     friends: [] } ] 

我在做什么错?

回答

3

你没有做错什么。这是设计。该查询是Charlie的findOne,然后填充,然后执行另一个查询以返回ref集合中的文档。

你可以得到最接近的是通过添加select到查询只返回朋友:

Person 
    .findOne({name: 'Charlie'}) 
    .select('friends') 
    .populate('friends') 
    .run(function(err, friends) { 
    if (err) throw err 
    console.log('JSON for friends is: ', friends); 
    db.disconnect(); 
    }); 

这将返回:

JSON for friends is: 
{ 
    _id: 4fb302beb7ec1f775e000003, 
    friends: 
    [ { name: 'Aaron', 
     age: 100, 
     _id: 4fb302beb7ec1f775e000001, 
     stories: [], 
     friends: [] }, 
     { name: 'Bill', 
     age: 97, 
     _id: 4fb302beb7ec1f775e000002, 
     stories: [], 
     friends: [] } ] } 
相关问题