Jason
Jason

Reputation: 37

How to query multiple collections in mongoose

I have two schema "Users" and "Books".

Users: _id, isActive type: boolean

Books: userid ref Users, name

I want to query Books which user's isActive is true.

I have one approach that is first query Users with isActive=true and return userid list, then query Books with userid in userid list.

Can anybody has the other better approach to query this situation? thanks.

Upvotes: 1

Views: 1606

Answers (2)

Talha Awan
Talha Awan

Reputation: 4619

Version 3.2 introduced $lookup, which works like left outer join in aggregation pipeline.

User.aggregate([
    {
        $match: {isActive: true}
    },
    {
        $lookup: //left outer join
        {
            from: "books",
            localField: "_id",
            foreignField: "userid",
            as: "books"
        }
    },
    {
        $unwind: "$books" // convert each element of "books" array into its own document
    },
    {
        $replaceRoot: { newRoot: "$books" } // remove "books" key. Bring its content out in the root
    }

]).exec(function(err, books) {
    // books with users isActive true
})

Note that, we used User to aggregate because we want to query isActive: true, but after processing the documents in the aggregation pipeline we get books at the end.

Upvotes: 1

Mohsen ZareZardeyni
Mohsen ZareZardeyni

Reputation: 946

It depends on problem and size of your collections! Your approach is good when you have limited active user. But if you have lot's of active users while your Book collection is small then I would suggest to load the books, and then check if each user is active or not!

Also if you've have lots of active users and lot's of books then storing User's active status inside Book wouldn't be a bad idea.

Upvotes: 0

Related Questions