How to fix DocumentNotFoundError: No document found for query in MongoDB
The DocumentNotFoundError occurs when MongoDB cannot find any documents matching your query criteria. This typically happens when querying with incorrect filters, accessing deleted documents, or working with empty collections. Understanding query patterns and validation can help prevent this error.
Quick fix
Fixes DocumentNotFoundError: No document found for query
// Check if document exists before attempting update
const existingDoc = await Model.findById(documentId);
if (!existingDoc) {
throw new Error(`Document with ID ${documentId} not found`);
}
// Or use findOne to check with custom query
const doc = await Model.findOne({ _id: documentId, status: "active" });
if (!doc) {
// Handle missing document appropriately
}- Verify the document ID exists in the database
- Use findOneAndUpdate with upsert option when appropriate
- Handle the error gracefully in your application
- Check your query filters and validation
// Check if document exists before attempting updateconst existingDoc = await Model.findById(documentId);if (!existingDoc) {throw new Error(`Document with ID ${documentId} not found`);}// Or use findOne to check with custom queryconst doc = await Model.findOne({ _id: documentId, status: "active" });if (!doc) {// Handle missing document appropriately}DocumentNotFoundError: No document found for query
What this error means
The DocumentNotFoundError is a common MongoDB error that occurs when a query operation fails to find any matching documents in the database. This error is particularly common in Mongoose ORM when using methods like `findByIdAndUpdate()`, `findOneAndUpdate()`, or `findOneAndDelete()` with the `new: true` option when no document matches the query criteria. In MongoDB, queries return null or empty arrays when no documents match, but Mongoose wraps this in a DocumentNotFoundError to provide better error handling. This helps developers distinguish between "no documents found" and other types of database errors. The error indicates that your application logic expects a document to exist but the database query returned no results. This can happen due to race conditions, incorrect IDs, deleted documents, or mismatched query criteria.
Typical symptoms
- Application throws "DocumentNotFoundError: No document found for query" when trying to update or delete documents
- API endpoints return 404 errors when attempting to modify resources
- Database operations fail silently in update operations with `new: true` option
- Console shows Mongoose error with stack trace pointing to findOneAndUpdate or similar methods
Common causes
- Querying with an incorrect or non-existent document ID
- Race conditions where a document is deleted between read and update operations
- Using outdated or cached IDs that no longer reference valid documents
- Incorrect query filters that don't match any documents in the collection
- Working with an empty collection or recently cleared database
- Case sensitivity issues in string-based queries
How to fix "DocumentNotFoundError: No document found for query"
First, check if the document you're trying to access actually exists in the database:
// Check if document exists before attempting update
const existingDoc = await Model.findById(documentId);
if (!existingDoc) {
throw new Error(`Document with ID ${documentId} not found`);
}
// Or use findOne to check with custom query
const doc = await Model.findOne({ _id: documentId, status: "active" });
if (!doc) {
// Handle missing document appropriately
}You can also check directly in MongoDB Compass or the mongo shell:
db.collection.find({ _id: ObjectId("your-document-id") })If you want to create a document if it doesn't exist, use the upsert: true option:
// This will create the document if it doesn't exist
const result = await Model.findOneAndUpdate(
{ _id: documentId },
{ $set: updateData },
{
new: true,
upsert: true, // Creates document if it doesn't exist
runValidators: true
}
);Note: Use upsert carefully as it can create documents unexpectedly. Make sure this aligns with your application logic.
Implement proper error handling to catch DocumentNotFoundError and respond appropriately:
try {
const updatedDoc = await Model.findByIdAndUpdate(
documentId,
updateData,
{ new: true, runValidators: true }
);
if (!updatedDoc) {
// Handle case where document doesn't exist
return res.status(404).json({
error: "Document not found",
message: `No document found with ID: ${documentId}`
});
}
res.json(updatedDoc);
} catch (error) {
if (error.name === "DocumentNotFoundError") {
return res.status(404).json({
error: "DocumentNotFoundError",
message: error.message
});
}
// Handle other errors
console.error("Update error:", error);
res.status(500).json({ error: "Internal server error" });
}Ensure your query filters are correct and match the actual data in your database:
// Common issues to check:
// 1. String vs ObjectId comparison
const doc = await Model.findOne({ _id: "string-id" }); // Wrong
const doc = await Model.findOne({ _id: new mongoose.Types.ObjectId("string-id") }); // Correct
// 2. Case sensitivity in string fields
const doc = await Model.findOne({ email: "User@Example.com" }); // May not match "user@example.com"
const doc = await Model.findOne({ email: /^user@example\.com$/i }); // Case-insensitive regex
// 3. Nested field queries
const doc = await Model.findOne({ "address.city": "New York" }); // Correct syntax
// 4. Date comparisons
const doc = await Model.findOne({
createdAt: {
$gte: new Date("2024-01-01"),
$lte: new Date("2024-12-31")
}
});Use MongoDB Compass to examine actual document structure and field values.
Add validation to prevent invalid IDs from reaching your database operations:
// Validate MongoDB ObjectId format
function isValidObjectId(id) {
return mongoose.Types.ObjectId.isValid(id) &&
(new mongoose.Types.ObjectId(id)).toString() === id;
}
// Use middleware to validate IDs
app.param("id", (req, res, next, id) => {
if (!isValidObjectId(id)) {
return res.status(400).json({
error: "Invalid ID format",
message: "ID must be a valid MongoDB ObjectId"
});
}
next();
});
// Clean up stale references in your application
// Remove references to deleted documents from caches or in-memory storesRegularly audit your database for orphaned references and implement cleanup routines.
Advanced notes
The DocumentNotFoundError is specific to Mongoose ORM and not native MongoDB. In native MongoDB driver, queries simply return null or empty results without throwing this specific error. Mongoose introduces this error to provide better developer experience and error handling.
Performance Considerations: When frequently encountering this error, consider:
1. Adding database indexes on frequently queried fields to improve lookup performance
2. Implementing request deduplication to prevent race conditions
3. Using database transactions for multi-document operations to maintain consistency
Edge Cases:
- When using replica sets, there might be read consistency issues where a document exists on primary but not yet replicated to secondaries
- In sharded clusters, document location might affect query results
- Time-series collections and views have different query behaviors
Security Implications: Always validate user input before constructing queries to prevent NoSQL injection attacks. Never use raw user input directly in query filters without proper sanitization.
Frequently asked questions
- What does "DocumentNotFoundError: No document found for query" mean?
- The DocumentNotFoundError is a common MongoDB error that occurs when a query operation fails to find any matching documents in the database. This error is particularly common in Mongoose ORM when using methods like findByIdAndUpdate(), findOneAndUpdate(), or findOneAndDelete() with the new: true option when no document matches the query criteria. In MongoDB, queries return null or empty arrays when no documents match, but Mongoose wraps this in a DocumentNotFoundError to provide better error handling.
- How do I fix "DocumentNotFoundError: No document found for query"?
- The DocumentNotFoundError occurs when MongoDB cannot find any documents matching your query criteria. This typically happens when querying with incorrect filters, accessing deleted documents, or working with empty collections. Understanding query patterns and validation can help prevent this error.
- What causes "DocumentNotFoundError: No document found for query"?
- Querying with an incorrect or non-existent document ID Race conditions where a document is deleted between read and update operations Using outdated or cached IDs that no longer reference valid documents
- Is the "DocumentNotFoundError: No document found for query" error serious?
- It is a medium-severity error โ more of a blocker than a risk. The steps above resolve it.
Official resources & further reading
- ๐MongoDB Official Documentation
- ๐mongoosejs.com - query(Official Docs)
- ๐mongodb.com - db.collection.findOneAndUpdate(Official Docs)
- ๐ฌstackoverflow.com - mongoose+documentnotfounderror(Stack Overflow)
- ๐github.com - issues(GitHub)