ArrC
ArrC

Reputation: 213

Query mongodb for conditional conditions

How do i query mongo for the list of all non-private blogs along with the private blogs of currently logged-in user.

Blog(collection):
_user_id: ref(User), title: String, body: String, private: Boolean, default:false

I can get all the non-private blogs with this query:

Blog.find({_user_id: req.user}).where('private', false).exec();

But I also want to get all the blogs which are marked private only by this current logged-in user.

Is this thing even possible using single query. Do I have to rely on advance mongodb features like map-reduce / aggregate .

Upvotes: 1

Views: 387

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 311835

You can use $or to include both cases in a single query:

Blog.find({$or: [
    // Non-private blogs
    {private: false},
    // Blogs of the current user
    {_user_id: req.user}
]}).exec(function(err, docs) { ... });

This will provide a union of the results of the two $or clauses.

Upvotes: 1

Related Questions