我想根据请求参数在猫鼬集合上自定义搜索火山口
Course.find(
{
instTypeId: 1,
status: 1,
"institute.instId": req.body.instId,
"institute.majorId": req.body.majorId
},
)
我试图这样做,但是如果req.intId或req.major id为空,则只会获取具有空Institute.instId的记录
如果req.intId或req.major或两者都不想在查找中包含它们
答案 0 :(得分:0)
您可以使用Object.assign
将值添加到搜索对象(如果存在):
let instId;
let majorId = 1;
if (instId){
search = Object.assign(search, {"institute.instId": instId});
}
if (majorId){
search = Object.assign(search, {"institute.majorId": majorId});
}
Course.find(search , (err, foundCourses) => {
// Do stuff
});
答案 1 :(得分:0)
假设您收到了经过解析的req.body
,那么快速而肮脏的方式可能是:
Course.find({
instTypeId: 1,
status: 1,
// if req.body.instId is 'undefined', then it returns false so the expression returns 'null'
"institute.instId": req.body.instId || null,
"institute.majorId": req.body.majorId || null
})
您可以用类似的方式构建查询对象:
var query = {}
if (req.body.instId) {
// using object destructuring
query = {..., "institute.instId": req.body.instId }
}
但是,建议根据用例设置一些验证
答案 2 :(得分:0)
let search = {
instTypeId: 1,
status: 1
};
if (req.body.instId) {
search["institute.instId"] = req.body.instId;
}
if (req.body.majorId) {
search["institute.majorId"] = req.body.majorId;
}
Course.find(search)
我这样做是为了自定义搜索列