简体   繁体   English

如何在sails.js中过滤填充值?

[英]How can I filter populated values in sails.js?

I have model User . 我有模特User To simplify my issue it has not attributes (except id that is produced by sails engine): 为了简化我的问题,它没有属性(除了由sails引擎生成的id):

module.exports = {

}

I have also model UserPost : 我还建模了UserPost

module.exports = {
    attributes: {
        user: {
            required: true,
            model: 'user'
        }
    }
}

I want to find posts of user with id equal to 42. I have that records in database, both user with id 42, and its posts. 我想查找id等于42的用户的帖子。我在数据库中有这些记录,id为42的用户及其帖子。

This doesn't work: 这不起作用:

UserPost.find().populate('user', {
    id: 42
}).exec(function(err, posts) {
    res.json(posts);
});

Of course, in this case I can just pass query criteria to find() . 当然,在这种情况下,我可以将查询条件传递给find() Anyway in general I should be able to find not only by id but the other attributes too. 无论如何,总的来说,我不仅可以找到id,还可以找到其他属性。

How can I do that? 我怎样才能做到这一点?

In fact the problem was my wrong understanding of what population criteria is. 事实上,问题是我对人口标准的错误理解。 The solution is 解决方案是

  • create one-to-many association for User and UserPost models UserUserPost模型创建一对多关联

  • find user and populate it to his post. 找到用户并将其填充到他的帖子中。 Something like: 就像是:

User.findOne({
    id: 42
}).populate('userPosts').exec(function(err, user) {
    res.json(user.userPosts);
});

This works well. 这很好用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM