Model.findById()

Parameters
Returns:
  • «Query»

Finds a single document by its _id field. findById(id) is almost* equivalent to findOne({ _id: id }). If you want to query by a document’s _id, use findById() instead of findOne().

The id is cast based on the Schema before sending the command.

This function triggers the following middleware.

  • findOne()

* Except for how it treats undefined. If you use findOne(), you’ll see that findOne(undefined) and findOne({ _id: undefined }) are equivalent to findOne({}) and return arbitrary documents. However, mongoose translates findById(undefined) into findOne({ _id: null }).

Example:

  1. // Find the adventure with the given `id`, or `null` if not found
  2. await Adventure.findById(id).exec();
  3. // using callback
  4. Adventure.findById(id, function (err, adventure) {});
  5. // select only the adventures name and length
  6. await Adventure.findById(id, 'name length').exec();