skip to Main Content

Trying to find a document by ObjectId in mongoose. The query returns an empty result but when applying the same query in the "MongoDB Compass" – it returns the document.

const mongoose = require("mongoose");

await CollectionModel.find({ "_id": new mongoose.Types.ObjectId(DOCUMENT_ID)});

MongoDB Compass

What are the possible reasons for the issue?

Note: searching with other properties except the "_id" works fine.

2

Answers


  1. your query in find is the DOCUMENT_ID is string because you add double quote

    CollectionModel.find({ "_id": new mongoose.Types.ObjectId("DOCUMENT_ID")})
    

    instead, it should just be

    CollectionModel.find({ "_id": new mongoose.Types.ObjectId(DOCUMENT_ID)})
    

    also make sure you use await

    await CollectionModel.find({ "_id": new mongoose.Types.ObjectId(DOCUMENT_ID)})
    

    mongoose.Types.ObjectId() is right but you can also just use the string just in case

     const DOCUMENT_ID = "614ad6b706f4d031e48b9430"
     await CollectionModel.find({ "_id": new mongoose.Types.ObjectId(DOCUMENT_ID)})
    
    Login or Signup to reply.
  2. you can use the findById() function and pass in the string form of the id. So:

    await CollectionModel.findById("The documents id")
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search