简体   繁体   English

Mongoose 查找不适用于查询 object

[英]Mongoose find is not working with query object

I am learning node.js with mongo db .我正在用mongo db学习node.js I have a code to fetch records and that works fine我有一个代码来获取记录并且工作正常

await studentModel.find({}, (err, data) => {
    if (err) throw err;
      students= data.map((d) => {
        return new InterviewQuestion(d['roll_no'], d['name']);
      });
    });

but when I want to filter them then the query doesn't return any record但是当我想过滤它们时,查询不会返回任何记录

await studentModel.find({sClass: sClass}, (err, data) => { //sClassis a field in document and also the name of variable
    if (err) throw err;
      students= data.map((d) => {
        return new InterviewQuestion(d['roll_no'], d['name']);
      });
    });

when you use async/await don't use callback and use try/catch in async/await approach so you can do like this当您使用 async/await 时,不要使用回调并在 async/await 方法中使用 try/catch,这样您就可以这样做

try {
  let data = await studentModel.find({});
  students = data.map((d) => {
    return new InterviewQuestion(d["roll_no"], d["name"]);
  });
} catch (err) {
  throw err;
}

try {
  let data = await studentModel.find({ sClass: sClass });
  students = data.map((d) => {
    return new InterviewQuestion(d["roll_no"], d["name"]);
  });
} catch (err) {
  throw err;
}

this query is correctly这个查询是正确的

await studentModel.find({ sClass: sClass })

also you can try this:你也可以试试这个:

await studentModel.find({ sClass})

your issue from another thing, because I tested the queries every things is OK你的问题来自另一件事,因为我测试了查询每件事都可以

I used a different name for the variable sClass and then it worked.我为变量sClass使用了不同的名称,然后它起作用了。 I am still wondering why it is not allowed to have a filter variable with the same name as of document field.我仍然想知道为什么不允许使用与文档字段同名的过滤器变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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