0

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']);
      });
    });
1
  • if you want to find main problem, you can add controller, route, schema to the question, and request Commented Jan 23, 2021 at 18:55

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

4 Comments

Why can't I used call back with async methods? I heard callback are best for handling asyn requests. Also my code without filter works.
where did you heard callback are best for handling async requests??
Everywhere, as an example w3schools.com/js/js_callback.asp
you can use async/await with try/catch togheter or a promise function without await with .then().catch() or a function with callback, there are 3 approach
0

I used a different name for the variable sClass and then it worked. I am still wondering why it is not allowed to have a filter variable with the same name as of document field.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.