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.
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.
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: "[email protected]" }); // May not match "[email protected]"
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.
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.
StaleShardVersion: shard version mismatch
How to fix "StaleShardVersion: shard version mismatch" in MongoDB
MongoOperationTimeoutError: Operation timed out
How to fix "MongoOperationTimeoutError: Operation timed out" in MongoDB
MongoServerError: PlanExecutor error during aggregation :: caused by :: Sort exceeded memory limit of 104857600 bytes, but did not opt in to external sorting. Aborting operation.
How to fix "QueryExceededMemoryLimitNoDiskUseAllowed" in MongoDB
MissingSchemaError: Schema hasn't been registered for model
How to fix "MissingSchemaError: Schema hasn't been registered for model" in MongoDB/Mongoose
CastError: Cast to ObjectId failed for value "abc123" at path "_id"
How to fix "CastError: Cast to ObjectId failed" in MongoDB