Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
282 views
in Technique[技术] by (71.8m points)

node.js - Mongoose find is not working with query object

I am learning node.js with mongo db. 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']);
      });
    });
question from:https://stackoverflow.com/questions/65858419/mongoose-find-is-not-working-with-query-object

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

when you use async/await don't use callback and use try/catch in async/await approach so you can do like this

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...