Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

356
Views
mongoose.findOne returns null

I am trying to retrieve todo by id. Code for getTodo service method is as below:

const getTodo = async (id, userId) => {
  const todo = await Todo.findOne({ id: id, userId: userId });
  return todo;
};

code from router which acts as a controller is as below:

router.get("/:id", tokenValidation.validate, async (req, res) => {
  const serverResponse = { ...defaultResponse };
  try {
    const decodedToken = jwt.decode(
      req.headers.authorization.split(" ")[1].trim()
    );
    const getTodo = await todoService.getTodo(req.params.id, decodedToken.id);
    serverResponse.status = 200;
    serverResponse.body = getTodo;
    serverResponse.message = "Get todo by id";
  } catch (error) {
    serverResponse.message = error.message;
  }

  return res.status(serverResponse.status).send(serverResponse);
});

But the result is always null, on calling:

http://localhost:3000/api/v1/todos/60422718e9db822de8531e87

{
    "status": 200,
    "message": "Get todo by id",
    "body": null
}

What is missing in findOne method. Todo with id exists in the collection but is not returned. Please let me know what is missing.

Thanks

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

You must use with AND operator

const getTodo = async(id, userId) => {
  const todo = await Todo.findOne({
    $and: [{
        _id: id
      },
      {
        userId: userId
      }
    ]
  });
  return todo;
};

So this will return results with the combined conditions.

over 4 years ago · Santiago Trujillo Report

0

const getTodo = async (id, userId) => {
  const todo = await Todo.findOne({ id: id, userId: userId });
  return todo;
};

mongoose does not have "id" property. it has _id so you should query:

const todo = await Todo.findOne({ _id: id, userId: userId })

you dont need to pass two arguments. they both reflect same. "id" is already unique. you could just query:

    const todo = await Todo.findById(id)
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!