Luja Shrestha
Luja Shrestha

Reputation: 2847

Query on associated value in sails

There are two tables, Books which has many-to-many association with Tags. How can the Book that have only particular tag id be found? I tried:

Book.find().populate("tag", where:{id: 1 }).exec(console.log)

But it gives all the books.

Upvotes: 0

Views: 64

Answers (2)

Jason Kulatunga
Jason Kulatunga

Reputation: 5894

If your looking for all books with a specific tagid, your going to want to do something like:

Tag
.findOne(1)
.populate('books')
.then(function(tag) {
    if (!tag) {
        res.serverError(error);
    } else {
        res.json(tag.books);
    }
});

Basically you want to look up the tag by id (1), and then populate the books association for that tag.

Upvotes: 2

Eugene Obrezkov
Eugene Obrezkov

Reputation: 2986

You must provide criteria in find(), not in populate.

Your fixed variant:

Book
    .find()
    .where({
        id: 1
    })
    .populate('tag')
    .exec(function(error, books) {
        if (error) {
            res.serverError(error);
        } else {
            res.json(books);
        }
    });

Upvotes: 0

Related Questions