How to Find a single document in MongoDB using Mongoose

Answer

To Find a single document in MongoDB using Mongoose is very easy as Mongoose interacts with the database through its models . A Mongoose model has several associated methods to help manage the interactions,

Mongoose query methods

Mongoose models have several methods available to solve with querying the database.
Below are the major used 

  1. find—General search based on a supplied query object
  2. findById—Looks for a specific ID
  3. findOne—Gets the first document to match the supplied query
  4. geoNear—Finds places geographically close to the provided latitude and longitude
  5. geoSearch—Adds query functionality to a geoNear operation

For finding a single database document with a known ID in MongoDB, Mongoose has the findById() method.

 

APPLYING THE FINDBYID METHOD TO THE MODEL

The findById() method accept a single parameter only:
the ID to look for. As it’s a model method, it’s applied to the model like this:
Loc.findById(id)
This method won’t start the database query operation; it tells the model what the
query will be. To start the database query, Mongoose models have an exec method.

RUNNING THE QUERY WITH THE EXEC METHOD

The exec method executes the query and passes a callback function that will run
when the operation is complete. The callback function should accept two parameters:
an error object and the instance of the found document. As it’s a callback function,
the names of these parameters can be whatever you like.

.findById(id)
.exec((err, name) => {
console.log("findById complete");
});

This approach ensures that the database interaction is asynchronous and, therefore,
doesn’t block the main Node process.

To find a Single subdocument, you first have to find the parent document, and then pinpoint the required document using its ID. When you’ve found the document, you can look for a specific subdocument.

 

All mongoose Questions

Ask your interview questions on mongoose

Write Your comment or Questions if you want the answers on mongoose from mongoose Experts
Name* :
Email Id* :
Mob no* :
Question
Or
Comment* :
 





Disclimer: PCDS.CO.IN not responsible for any content, information, data or any feature of website. If you are using this website then its your own responsibility to understand the content of the website

--------- Tutorials ---