为什么MongooseJS没有正确填充我的字段?

时间:2012-05-16 01:38:58

标签: mongodb mongoose populate

我正在尝试调整此处的示例

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在friends字段中使用ObjectIds并使用匹配的对象(aaron和bill)填充数组。换句话说,更多的是

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

我做错了什么?

1 个答案:

答案 0 :(得分: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: [] } ] }