简体   繁体   English

如何通过在nodejs中使用多个字段的搜索操作使用mongoose获取与mongodb中的字段匹配的所有文档

[英]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);
      });
}

` `

I want all the documents which matches the fields, the user may or may not give all the fields to search and retrieve.我想要所有与字段匹配的文档,用户可能会也可能不会提供所有要搜索和检索的字段。

I think this problem occurs because you are using the $or this makes it so one filters for instance the name with a value, but then it does an or on the email field which if empty just returns all the documents, I think you need some logic to check if a value and if it is empty not return it and I think for your use case you do not need the $or , I did this in my application like this:我认为出现此问题是因为您正在使用$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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM