user3766930
user3766930

Reputation: 5839

How to combine AND with OR in mongoose?

I realized that when in node.js I build a query such as:

if (hashtagsInput != undefined) {
    var hashtags = hashtagsInput.split(",");
    for(var i=0; i<hashtags.length; i++) {
        query = query.or([{ 'hashtags': hashtags[i] }]);
    }
}

if (friends != undefined) {
    var friendsSplitted = friends.split(",");
    for(var i=0; i<friendsSplitted.length; i++) {
        query = query.or([{ 'facebook_username': friendsSplitted[i] }]);
    }
}

then the query is:

..., '$or': [ { hashtags: 'test1' }, { hashtags: 'test2' }, {
     facebook_username: 'XXXXXXXXXXXX' }, { facebook_username: 'YYYYYYYYYYYYYYY' },
     { facebook_username: 'ZZZZZZZZZZZZ' }],...

and that will find all records that either have hashtags test1 or test2 OR have fb_username XXXXXX or YYYYYYY or ZZZZZZZ.

But how can I write in the node.js code the query so that when user puts hashtags then the query fetches entries that have test1 or test2 AND fb_username XXXXXX or YYYYYYY or ZZZZZZZ?

If user does not provide any hashtags then it could fetch only fb_accounts and the other way around - if user does not provide fb, then it pays attention only to hashtags.

Upvotes: 0

Views: 327

Answers (1)

Puneet Singh
Puneet Singh

Reputation: 3543

I suppose you want to put AND operator between hashes and username when both are provided, and when one of them is provided you want to search with them only.

var query = {};
query.$and = [];

if (hashtagsInput != undefined) {
    var hashtags = hashtagsInput.split(",");
    query.$and.push({"hashtags":{$in: hashtags}});
}

if (friends != undefined) {
    var friendsSplitted = friends.split(",");
    query.$and.push({"facebook_username":{$in: friendsSplitted}});
}

You can use $in operator to apply Or condition as you can pass directly array, you don't need to apply for loop.

When user puts hashtags and username both then the query fetches entries that have (test1 or test2) AND (fb_username XXXXXX or YYYYYYY or ZZZZZZZ)

Upvotes: 1

Related Questions