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) withfindOne()(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:
| Usage | Description | Example |
|---|---|---|
| Find all documents | Returns all documents in the collection | Model.find({}) |
| Find with filter | Returns documents matching criteria | Model.find({ age: { $gte: 18 } }) |
| Find specific fields | Returns only selected fields | Model.find({}, 'name age') |
| Find one document | Returns first matching document | Model.findOne({ name: 'Alice' }) |
| Sort results | Sort documents by field | Model.find({}).sort({ age: -1 }) |
| Limit results | Limit number of documents returned | Model.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.