水线包含关联属性?

时间:2015-08-04 15:20:19

标签: javascript mongodb sails.js contains waterline

我有一个用户填充的模型。所以我想查找其中一个用户= someString。

所以使用Waterline我可以做到这一点

        Partie.find().populate('users').where({category:{'contains':'sport'}}).exec(function(e,r){
        console.log(r);
        res.json(200,r);
    });

但是如何在'用户'?这是一个数组。

"users": [
  {
    "username": "firstUser",
    "createdAt": "2015-07-30T15:33:57.662Z",
    "updatedAt": "2015-07-30T15:33:57.662Z",
    "id": "55ba43e58cce9ee80865271b"
  },
  {
    "username": "someUsername",
    "createdAt": "2015-08-04T12:14:50.291Z",
    "updatedAt": "2015-08-04T12:14:50.291Z",
    "id": "55c0acba2d1502ed2faf2b3b"
  }
],...

不确定这是否可行。随意提出替代方案

1 个答案:

答案 0 :(得分:3)

您可以将第二个参数传递给使用包含查询条件的填充,例如:

 Partie.find().populate('users', {where: {username: "someUsername"}})...

根据我的经验(使用最新的水线),上面的示例仅填充与给定用户名匹配的用户到Partie对象中。

但是,在我的机器上,它并不限制从搜索查询返回的“派对”(这可能与我的水线/ postgres适配器版本有关)。我通过在返回之后过滤完整数组来解决了这个问题(使用lodash):

 res.json(_.filter(parties, function(party){
    // Pluck all usernames and check if 'someUserName' is attending this party
    return _.contains(_.pluck(party.users, 'username'), 'someUserName');
 }));

请注意,对于大型数据集,使用上述示例的过滤器是不可取的!

相关问题