How to combine AND with OR in mongoose?

血红的双手。 提交于 2019-12-25 08:00:16

问题


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.


回答1:


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)



来源:https://stackoverflow.com/questions/40053692/how-to-combine-and-with-or-in-mongoose

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!