Master MongoDB operations using Mongoose, the popular Object Data Modeling (ODM) library for Node.js. This guide covers 15 essential query methods with real-world examples to help you interact with databases efficiently.
1. deleteMany()
Delete multiple documents matching criteria.
await BlogPost.deleteMany({ status: 'draft' });
Use case: Bulk-clean outdated records.
2. deleteOne()
Remove first matching document.
await User.deleteOne({ email: 'inactive@test.com' });
Tip: Safer than deleteMany for single document removal.
3. find()
Retrieve multiple documents with filtering.
const activeUsers = await User.find({ isActive: true });
Pro tip: Chain .limit(10)
for pagination.
4. findById()
Fetch single document using ID.
const post = await BlogPost.findById('5f8d0d55b54764421b4396e8');
Essential for: Single resource retrieval.
5. findByIdAndDelete()
Find by ID and delete in one operation.
const deletedItem = await Product.findByIdAndDelete(productId);
Returns: The deleted document.
6. findByIdAndRemove()
Legacy method similar to findByIdAndDelete.
const removedUser = await User.findByIdAndRemove(userId);
Note: Prefer findByIdAndDelete
for new projects.
7. findByIdAndUpdate()
Update document by ID with options.
const updatedPost = await BlogPost.findByIdAndUpdate(
postId,
{ $set: { title: 'New Title' } },
{ new: true }
);
Key option: { new: true }
returns updated document.
8. findOne()
Get first matching document.
const admin = await User.findOne({ role: 'admin' });
Use case: Unique field lookups (email
, username
).
9. findOneAndDelete()
Find and delete first match.
const deletedComment = await Comment.findOneAndDelete({
spam: true
});
Ideal for: Conditional single deletions.
10. findOneAndReplace()
Replace entire document.
const replacedDoc = await Profile.findOneAndReplace(
{ userId: '123' },
newProfileData
);
Warning: Replaces all fields except _id
.
11. findOneAndUpdate()
Update specific fields in first match.
const updatedOrder = await Order.findOneAndUpdate(
{ status: 'pending' },
{ $set: { status: 'processed' } },
{ returnDocument: 'after' }
);
Best practice: Use $set operator for partial updates.
12. replaceOne()
Replace first matching document.
await Product.replaceOne(
{ sku: 'OLD123' },
newProductData
);
Difference from update: Replaces entire document.
13. updateMany()
Bulk update documents.
await User.updateMany(
{ lastLogin: { $lt: '2023-01-01' } },
{ $set: { status: 'inactive' } }
);
Caution: Always test with find()
first.
14. updateOne()
Update first matching document.
await Post.updateOne(
{ slug: 'old-post' },
{ $set: { slug: 'new-post' } }
);
Safer than: updateMany for single document edits.
Best Practices for Mongoose Queries
- Always validate input before database operations
- Use transactions for critical operations
- Index frequently queried fields
- Handle errors with
try/catch
blocks - Sanitize user input to prevent NoSQL injection