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
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.