![](/img/trans.png)
[英]How to calculate sum of fields from mongodb collection documents using mongoose
[英]how to get all the documents that are matching the fields in mongodb using mongoose by using search operation with multiple fields in nodejs
`
const getCandidates = (req,res,next) => {
console.log(req.params);
Candidate.find({
$or:[
{"name":req.params.name},
{"email":req.params.email},
{"role":req.params.role},
{"status":req.params.status}
]}
,
function(err, result) {
if(err) { console.log(err);
throw err;
}
res.json(result);
});
}
`
我想要所有與字段匹配的文檔,用戶可能會也可能不會提供所有要搜索和檢索的字段。
我認為出現此問題是因為您正在使用$or
這使得它可以過濾例如具有值的name
,但隨后它在email
字段上執行或操作,如果該字段為空則只返回所有文檔,我認為您需要一些檢查值是否為空的邏輯不返回它,我認為對於您的用例,您不需要$or
,我在我的應用程序中這樣做是這樣的:
const query = Object.entries(req.params.reduce((acc, [key, value]) => {
if (value !== "") {
return { ...acc, [key]: value };
}
return acc
, {});
const result = await Candidate.find(query);
res.json(result);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.