mongodb Errors
20 error patterns
MongoDB duplicate key violation
E11000 duplicate key error
- •Check for existing documents before insert, or use upsert
- •Verify your unique index fields don't have null values creating conflicts
Mongoose required field validation error
ValidationError.*Path.*is required|validation failed.*required
- •Ensure all required fields defined in schema are provided before save()
- •Check for typos in field names — Mongoose silently ignores unknown fields
Mongoose CastError invalid ObjectId
CastError.*Cast to ObjectId failed
- •Validate the ID format before querying: mongoose.Types.ObjectId.isValid(id)
- •Check route params aren't receiving unexpected values (e.g., 'favicon.ico')
Mongoose operation buffering timed out
buffering timed out|connection.*buffering.*timed
- •Ensure mongoose.connect() is called and resolves before running queries
- •Check MongoDB server is running and connection string is correct
MongoDB transaction error
Transaction.*aborted|TransientTransactionError|WriteConflict
- •Implement retry logic for TransientTransactionError (automatic in newer drivers)
- •Ensure you're using a replica set — transactions require replica sets
MongoDB Atlas connection/authentication failure
MongoServerError.*Authentication failed|MongooseServerSelectionError.*ECONNREFUSED
- •Whitelist your IP in Atlas Network Access settings
- •Verify username/password are URL-encoded if they contain special characters
Mongoose optimistic concurrency version error
VersionError.*No matching document.*for.*save|document.*modified
- •Re-fetch the document and reapply changes before saving again
- •Use findOneAndUpdate() for atomic updates instead of find-modify-save
Mongoose populate path error
MongooseError.*populate.*path|Cannot populate.*unknown
- •Verify the ref in schema matches the registered model name exactly
- •Check that the field being populated is of type ObjectId with a ref
MongoDB query timeout exceeded
exceeded.*timeout|cursor.*timed out|MaxTimeMSExpired
- •Add indexes for the fields used in query filters and sorts
- •Use .explain() to identify collection scans and missing indexes
MongoDB BSON size or type error
BSONTypeError|Cannot create.*BSON|document.*too large|16MB
- •Documents cannot exceed 16MB — split large data into multiple documents or use GridFS
- •Check that field values are valid BSON types (no undefined, functions, or symbols)
Mongoose model not registered
Schema hasn't been registered.*model|MissingSchemaError
- •Register the model with mongoose.model('Name', schema) before referencing it
- •Check circular imports — model file may not have executed before reference
Mongoose model compiled multiple times
Cannot overwrite.*model once compiled|OverwriteModelError
- •Use mongoose.models.Name || mongoose.model('Name', schema) pattern
- •In Next.js/serverless, check if model exists before redefining
MongoDB unknown query operator
MongoError.*\$.*unknown operator|bad query.*operator
- •Check operator spelling ($gt, $gte, $in, $regex, etc.)
- •Ensure filter objects aren't accidentally nested: {field: {$gt: 5}} not {field: {gt: 5}}
MongoDB conflicting index definition
MongoError.*index.*already exists.*different options
- •Drop the existing index before creating with new options: collection.dropIndex()
- •Use the same index name or let MongoDB auto-generate it
MongoDB connection pool destroyed
Topology was destroyed|topology.*closed|pool.*destroyed
- •Don't call mongoose.disconnect() while operations are pending
- •Handle SIGINT/SIGTERM gracefully — close connections after pending ops complete
MongoDB Change Stream error
ChangeStream.*error|change stream.*closed|resume token
- •Store the resume token and use it to resume the stream after disconnection
- •Ensure oplog has sufficient size for your change stream throughput
MongoDB aggregation pipeline error
Aggregate.*error|\$lookup.*failed|pipeline.*stage.*invalid
- •Check stage order — $match before $group for performance, $project field names
- •Verify $lookup foreign collection and field names match exactly
Mongoose discriminator error
discriminator.*error|Cannot create.*discriminator
- •Define the base schema first, then add discriminators on the base model
- •Ensure discriminator key field is not redefined in child schema
MongoDB TLS/SSL connection error
MongoDB.*SSL.*TLS.*error|certificate.*verify|UNABLE_TO_VERIFY_LEAF_SIGNATURE
- •Add tls=true&tlsCAFile=path/to/ca.pem to connection string for Atlas
- •For self-signed certs in dev, use tlsAllowInvalidCertificates=true
MongoDB cursor already closed/exhausted
cursor.*already.*closed|Cursor.*exhausted|MongoCursorExhaustedError
- •Don't reuse cursors — create a new query/find() for each iteration
- •Increase cursor timeout with noCursorTimeout option for long-running reads