0

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

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

我究竟做错了什么?

4

1 回答 1

3

你没有做错任何事。这是设计使然。该查询是针对 Charlie 的,populate 然后执行另一个查询以从集合findOne中返回文档。ref

您可以获得的最接近的方法是select在查询中添加 a 以仅返回朋友:

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: [] } ] }
于 2012-05-16T17:03:18.653 回答