Home > Software design >  MongoDB (mongoose) - find by ObjectId returns empty result
MongoDB (mongoose) - find by ObjectId returns empty result

Time:11-27

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.

CodePudding user response:

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)})

CodePudding user response:

you can use the findById() function and pass in the string form of the id. So:

await CollectionModel.findById("The documents id")
  • Related