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)});
What are the possible reasons for the issue?
Note: searching with other properties except the "_id" works fine.
2
Answers
your
query
in find is theDOCUMENT_ID
is string because you add double quoteinstead, it should just be
also make sure you use
await
mongoose.Types.ObjectId()
is right but you can also just use thestring
just in caseyou can use the
findById()
function and pass in the string form of the id. So: