0
0
MongodbHow-ToBeginner · 4 min read

How to Find Documents Using Mongoose: Syntax and Examples

To find documents using mongoose, use the Model.find() method with an optional filter object to specify criteria. This method returns all matching documents as an array, or all documents if no filter is given.
📐

Syntax

The basic syntax to find documents in Mongoose is:

  • Model.find(filter, projection, options, callback)

Here:

  • Model is your Mongoose model representing a collection.
  • filter is an object specifying search criteria (empty object {} finds all documents).
  • projection (optional) specifies which fields to include or exclude.
  • options (optional) can control sorting, limiting, etc.
  • callback (optional) is a function to handle results asynchronously.

If you omit the callback, find() returns a Query that you can await or use .then() with.

javascript
Model.find({ age: { $gte: 18 } }, 'name age', { sort: { age: 1 } }, function(err, docs) {
  if (err) return console.error(err);
  console.log(docs);
});
💻

Example

This example shows how to connect to MongoDB, define a simple User model, and find all users aged 18 or older. It prints the matching users' names and ages.

javascript
const mongoose = require('mongoose');

async function run() {
  await mongoose.connect('mongodb://localhost:27017/testdb');

  const userSchema = new mongoose.Schema({
    name: String,
    age: Number
  });

  const User = mongoose.model('User', userSchema);

  // Find users aged 18 or older
  const adults = await User.find({ age: { $gte: 18 } }, 'name age').sort({ age: 1 });

  console.log(adults);

  await mongoose.disconnect();
}

run().catch(console.error);
Output
[ { _id: '...', name: 'Alice', age: 18 }, { _id: '...', name: 'Bob', age: 22 } ]
⚠️

Common Pitfalls

Common mistakes when finding documents with Mongoose include:

  • Not awaiting the find() call or not using a callback, which leads to unresolved promises.
  • Passing an incorrect filter object that matches no documents.
  • Confusing find() (returns array) with findOne() (returns single document).
  • Not handling errors in callbacks or async/await.

Example of wrong and right usage:

javascript
// Wrong: forgetting to await or use callback
async function example() {
  const users = User.find({ age: { $gte: 18 } });
  console.log(users); // Prints a Query object, not results

  // Right: using await
  const usersCorrect = await User.find({ age: { $gte: 18 } });
  console.log(usersCorrect);
}

example().catch(console.error);
📊

Quick Reference

Here is a quick summary of common find() usages:

UsageDescriptionExample
Find all documentsReturns all documents in the collectionModel.find({})
Find with filterReturns documents matching criteriaModel.find({ age: { $gte: 18 } })
Find specific fieldsReturns only selected fieldsModel.find({}, 'name age')
Find one documentReturns first matching documentModel.findOne({ name: 'Alice' })
Sort resultsSort documents by fieldModel.find({}).sort({ age: -1 })
Limit resultsLimit number of documents returnedModel.find({}).limit(5)

Key Takeaways

Use Model.find(filter) to get all matching documents as an array.
Await the find() call or provide a callback to get results properly.
An empty filter {} returns all documents in the collection.
Use projection to select which fields to return.
Handle errors in callbacks or try/catch with async/await.