javascript - 水线包含关联属性?

标签 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"
  }
],...

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

最佳答案

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

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

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

但是,在我的机器上,它不限制从搜索查询返回的“派对”(也许这与我的 waterline/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');
 }));

请注意,对于大型数据集,不建议使用像上面示例这样的过滤器!

关于javascript - 水线包含关联属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31813154/

相关文章:

javascript - 选择更改数据属性

node.js - 当 graphQL 的查询从 mongodb 返回空数据时,你应该检查什么?

node.js - 将图像从 URL 保存到 node.js 中的 S3

node.js - 更新项目时如何防止 mongoDB 中的重复项目

javascript - 如何路由到 sails.js 中的函数

Sails.js 在生产环境中重定向到 example.com

javascript - 简化 jQuery 函数

javascript - 使用键更改数组值的索引

javascript - 使combineLatest 'forget'成为RxJS中的最后一次调用

java - 使用 UTC 时区解析 ISO8601 日期字符串到日期