MongoDB via Mongoose JS – What is findByID?
MongoDB via Mongoose JS – What is findByID?
findById
is a convenience method on the model thats provided by Mongoose to find a document by its _id. The documentation for it can be found here.
Example:
// Search by ObjectId
var id = 56e6dd2eb4494ed008d595bd;
UserModel.findById(id, function (err, user) { ... } );
Functionally, its the same as calling:
UserModel.findOne({_id: id}, function (err, user) { ... });
Note that Mongoose will cast the provided id
value to the type of _id
as defined in the schema (defaulting to ObjectId).
If the schema of id is not of type ObjectId you cannot operate with function :
findbyId()
MongoDB via Mongoose JS – What is findByID?
As opposed to find() which can return 1 or more documents,
findById() can only return 0 or 1 document.
Document(s) can be thought of as record(s).