sails js mongodb populate

4

我希望使用Sails js和MongoDB的.populate()方法,所以我做了以下操作:

我正在使用最新版本的Sails、MongoDB和Node。

我的模型如下:

// User.js
module.exports = {
  attributes: {
    name: {
      type: 'string'
    },
    pets: {
      collection: 'pet',
      via: 'owner'
    }
  }
};


// Pet.js
module.exports = {
  attributes: {
    name: {
      type: 'string'
    },

    owner: {
      model: 'user'
    }
  }
};

我使用了与文档相同的以下内容:

User.find()
.populate('pets')
.exec(function(err, users) {
  if(err) return res.serverError(err);
  res.json(users);
});

但是我得到了以下输出:
[
  {
    "pets": [],
    "id": "58889ce5959841098d186b5a",
    "firstName": "Foo",
    "lastName": "Bar"
  }
]

创建了一个问题:https://github.com/balderdashy/sails-mongo/issues/449 - Craig van Tonder
1
请在 config/model.js 文件中确保您有 migrate: 'safe' - Craig van Tonder
1个回答

2
如果你只需要查询狗的信息,你可以反转查询。
Pet.find() //or what you want with {}
 .populate('users')
 .exec(err, petsWithUsers)

但如果没有:
User.find()
      .populate('pets')
      .exec(err, users) ...

这将返回所有用户 (User.find()),并仅填充类型为狗的宠物 (populate('pets', {type: 'dog'}))。在这种情况下,您的结果中将有没有狗的用户。
更多信息和参考资料请点击此处

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接