Find By ID in Mongoose

In Mongoose, the Model.findById() function is used to find one document by its _id . The findById() function takes in a single parameter, the document id. It returns a promise that resolves to the Mongoose document if MongoDB found a document with the given id , or null if no document was found.

const schema = new mongoose.Schema({ _id : Number }, { versionKey : false }); const Model = mongoose.model( 'MyModel' , schema); await Model.create({ _id : 1 }); await Model.findById( 1 ); await Model.findById( 2 );

When you call findById(_id) , Mongoose calls findOne({ _id }) under the hood. That means findById() triggers findOne() middleware.

const schema = new mongoose.Schema({ _id : Number }, { versionKey : false }); schema.pre( 'findOne' , function ( ) { console .log( 'Called `findOne()`' ); }); const Model = mongoose.model( 'MyModel' , schema); await Model.create({ _id : 1 }); await Model.findById( 1 );

Mongoose casts queries to match your schema. That means if your _id is a MongoDB ObjectId, you can pass the _id as a string and Mongoose will convert it to an ObjectId for you.

const _id = '5d273f9ed58f5e7093b549b0' ; const schema = new mongoose.Schema({ _id : mongoose.ObjectId }, { versionKey : false }); const Model = mongoose.model( 'MyModel' , schema); await Model.create({ _id : new mongoose.Types.ObjectId(_id) }); typeof _id; const doc = await Model.findById(_id); typeof doc._id; doc._id instanceof mongoose.Types.ObjectId;

Want to become your team's MongoDB expert? "Mastering Mongoose" distills 8 years of hard-earned lessons building Mongoose apps at scale into 153 pages. That means you can learn what you need to know to build production-ready full-stack apps with Node.js and MongoDB in a few days. Get your copy!

More Mongoose Tutorials