【问题标题】:Waterline contains on association attributes?水线是否包含关联属性?
【发布时间】:2015-08-04 15:20:19
【问题描述】:

我有一个填充了用户的模型。所以我想找到其中一个用户 = 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"
  }
],...

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

【问题讨论】:

  • 明确一点:您是否正在尝试向下填充多个级别?或者你只是想过滤用户数组?
  • 不,它已经满足我的需要。所以我有一个由用户填充的“游戏”。所以是的,我想过滤用户数组。类似 Game.find().populate('users').where({users.username:{'contains':'someUser'}}) 但这是无效的

标签: javascript mongodb sails.js contains waterline


【解决方案1】:

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

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

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

但是,在我的机器上,它不限制从搜索查询返回的“Parties”(可能这与我的水线/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');
 }));

请注意,对于大型数据集,不建议使用类似上述示例的过滤器!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-20
    • 1970-01-01
    • 2017-02-11
    • 2017-12-04
    • 2011-03-28
    • 2021-10-30
    相关资源
    最近更新 更多