0

I have model User. To simplify my issue it has not attributes (except id that is produced by sails engine):

module.exports = {

}

I have also model 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.

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(). Anyway in general I should be able to find not only by id but the other attributes too.

How can I do that?

Boris Zagoruiko
  • 12,705
  • 15
  • 47
  • 79

1 Answers1

0

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

  • 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.

Boris Zagoruiko
  • 12,705
  • 15
  • 47
  • 79
  • @zieglar. Because I want to be able to find not only by id. I mention it in the end of the question. With this approach, I can find for example posts of user by giver username or posts of users that was registered last month and so on. Not my downvotes, by the way. – Boris Zagoruiko Mar 03 '15 at 09:59