Skip to content Skip to sidebar Skip to footer

Mongo Using Mongoose In Node Want To Use Or And In Query

I have a situation where I have to check name of the company and code of the company and if both match with existing than it should say exists, or if one of them is matched in exis

Solution 1:

You can use $or operator

let filter = {
     "$or":[
             name: { $regex: newRegExp(`^${company.name}$`, 'i') },
             company_code: { $regex: newRegExp(`^${company.company_code}$`, 'i') 
            ]
}
}
cModel.find(filter, function (err, docs) {
                        if (docs.length) {
                            result.error = "Name already exists: " + company.name;
                            console.log("Name already exists", null);
                            let resp = api_respose.getSuccessResponse(process.env.WEB_URI, result.error);
                            resolve(resp);
                        }
else{
 ///saving here
}

refer https://docs.mongodb.com/manual/reference/operator/query/or/ for more info

Solution 2:

If I have correctly understood, you need using $or inside of $and function in Mongodb or mongoose, both of them supports these two functions. For example (in mongoose):

cModel.find(
        {
            $and: [
                {
                    $or: [
                        { name: { $regex: newRegExp(`^${company.name}$`, 'i') } },
                        { company_code: { $regex: newRegExp(`^${company.company_code}$`, 'i') } }
                    ]
                },
                {
                    is_delete: true
                }
            ]
        }, function (err, docs) { 
            if(docs){
                // throw error!
            } if (!docs) {
                // enter your new doc here with cModel.create(yourDoc, function(error, data){});
            }
        }
    );

complete documentation for this function is here:

https://docs.mongodb.com/manual/reference/operator/query/and/

Post a Comment for "Mongo Using Mongoose In Node Want To Use Or And In Query"