mongo using mongoose in node want to use or and in query

后端 未结 2 449
半阙折子戏
半阙折子戏 2021-01-23 20:54

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 e

2条回答
  •  太阳男子
    2021-01-23 21:47

    You can use $or operator

      let filter = {
         "$or":[
                 name: { $regex: new RegExp(`^${company.name}$`, 'i') },
                 company_code: { $regex: new RegExp(`^${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

提交回复
热议问题