Mongo with mongoose

How to find document byId using mongoose in express-node app

Mongoose is MongoDB driver module which provide REST features to build faster MongoDB apps with Nodejs.

Mongo Object Id

MongoDB object ID is an automatically generated multipurpose number. In our case we can use it to show up the document. In fact the Object ID consist of date and a unique random number.

Find records using MongoDB ObjectId

  Post.findById(pid,function (error, post) {
       if (error) return handleError(error)
          if (post) {
               console.log("Full post :" + post);

Using the findById method of mongoose model class allows us to find the document using MongoDB object Id and return result to the call back function in JavaScript style.

We can also use an asynchronous method find documents in Mongoose as follows

const post=await Post.findById(id)

and the resulted document will be

That’s it. Following mongoose posts deserve your attention

Published by


A developer,teacher and a blogger obsessed with Python,Dart and open source world from India

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.