【问题标题】:Why doesn't MongooseJS correctly populate my fields?为什么 MongooseJS 不能正确填充我的字段?
【发布时间】:2012-05-17 01:03:18
【问题描述】:

我正在尝试调整这里的示例

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

我做错了什么?

【问题讨论】:

    标签: mongodb mongoose populate


    【解决方案1】:

    你没有做错任何事。这是设计使然。该查询是 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: [] } ] }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-20
      • 2020-04-08
      • 2014-08-01
      • 1970-01-01
      相关资源
      最近更新 更多