2012-05-16 336 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: [] } ] } 
相關問題