MongoDB errors

MongoDB and Mongoose errors — connection strings, authentication, validation and duplicate keys.

CodeErrorWhat it means
Document failed validation MongoDB: MongoServerError: Document failed validation (code 121) The collection has a JSON Schema validator and the inserted/updated document doesn’t satisfy it.
MongoParseError MongoDB: MongoParseError: Invalid scheme, expected connection string to start with "mongodb://" or "mongodb+srv://" The connection string is missing, malformed, or the environment variable holding it is undefined.
Sort/Group exceeded memory limit of 100 MB (allowDiskUse) MongoServerError: Exceeded memory limit for $group, but didn't allow external sort. Pass allowDiskUse:true to opt in An aggregation stage needed more than 100 MB of RAM and spilling to disk wasn't enabled.
MongoServerError: not authorized on db to execute command MongoServerError: command find requires authentication / not authorized on mydb to execute command { find: "users" } The connection is authenticated as a user without privileges for that action — or isn't authenticated at all.
querySrv ENOTFOUND _mongodb._tcp MongoDB Atlas: Error: querySrv ENOTFOUND _mongodb._tcp.cluster0.abcde.mongodb.net The driver couldn't resolve the `mongodb+srv://` SRV record for your cluster.
bad auth : Authentication failed MongoDB: MongoServerError: bad auth : Authentication failed (code 8000 / 18) MongoDB (often Atlas) rejected the username/password in the connection string.
VersionError: No matching document found for id Mongoose: VersionError: No matching document found for id "5f..." version 3 modifiedPaths "items" Mongoose tried to save a document whose array was changed by someone else since you loaded it (optimistic con…
MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017 MongoDB: MongoServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017 The driver couldn't connect to a MongoDB server on localhost:27017 — nothing is listening there.
Mongoose: Model.find() no longer accepts a callback MongooseError: Model.find() no longer accepts a callback Mongoose 7+ removed callback support from queries; they return promises.
mongod exited with code 14 (data dir permission / lock) mongod: Process exited with status 14 — Exception in initAndListen: IllegalOperation: Attempted to create a lock file on a read-only directory `mongod` couldn't start because the data directory or log/socket file isn't writable or already locked.
Secondary too stale to catch up (RECOVERING) MongoDB: We are too stale to use X as a sync source / replSet too stale to catch up — member in RECOVERING state A secondary fell so far behind that the primary's oplog no longer covers the gap, so it can't resync by repla…
StrictPopulateError: Cannot populate path because it is not in your schema Mongoose 6+: StrictPopulateError: Cannot populate path `author` because it is not in your schema `populate('author')` references a field that isn't defined in the schema with a `ref`.
AlreadyInitialized: already initialized MongoServerError: already initialized (rs.initiate on a configured replica set) `rs.initiate()` was called on a node that already has a replica set configuration.
MongoServerError: operation exceeded time limit MongoServerError: operation exceeded time limit (MaxTimeMSExpired) / Query timed out A query ran longer than `maxTimeMS` (or the driver's socket/timeouts) and was aborted.
Transaction numbers are only allowed on a replica set member or mongos MongoServerError: Transaction numbers are only allowed on a replica set member or mongos You started a transaction (or used retryWrites) on a standalone MongoDB server, which doesn't support them.
Could not find host matching read preference MongoServerSelectionError: Could not find host matching read preference { mode: "secondary" } for set rs0 The requested read preference (secondary, nearest with tags) matches no available member.
mongo: command not found (use mongosh) MongoDB: bash: mongo: command not found / zsh: command not found: mongo The legacy `mongo` shell was removed from MongoDB 6.0+ installs; the shell is now `mongosh`, or MongoDB isn't…
Can't connect from another host (bindIp 127.0.0.1) MongoDB: connection refused / timed out from a remote host — mongod bindIp defaults to 127.0.0.1 MongoDB only listens on localhost by default, so remote clients can't connect.
Unclean shutdown: mongod.lock not empty / repair needed MongoDB: Detected unclean shutdown - /var/lib/mongodb/mongod.lock is not empty MongoDB wasn't shut down cleanly (crash/power loss), so it warns or refuses to start without recovery.
mongod killed by OOM killer MongoDB: Out of memory: Killed process (mongod) — WiredTiger cache + queries exhausted RAM The Linux OOM killer terminated `mongod` because the host ran out of memory.
rs.initiate failed: member not reachable / no host described in new configuration MongoDB: replSetInitiate quorum check failed: Could not connect to mongo2:27017 / No host described in new configuration 1 for replica set rs0 maps to this node `rs.initiate()`/`rs.add()` couldn't reach a listed member or the config doesn't include the current node's ho…
WiredTiger: No space left on device MongoDB: WiredTiger error (28) [...] No space left on device / Fatal assertion 28558 ... disk full MongoDB ran out of disk space on the data volume and stopped or refuses writes.
MissingSchemaError: Schema hasn't been registered for model Mongoose: MissingSchemaError: Schema hasn't been registered for model "User". Use mongoose.model(name, schema) You used `populate()`/`ref` for a model that hasn't been registered yet.
OverwriteModelError: Cannot overwrite model once compiled Mongoose: OverwriteModelError: Cannot overwrite `User` model once compiled. `mongoose.model('User', schema)` was called twice with the same name, typically from hot reloading.
MongoParseError: Password contains unescaped characters MongoParseError: URI malformed, cannot be parsed / Password contains unescaped characters The connection string contains characters in the user or password that must be percent-encoded.
Atlas: bad auth: Authentication failed MongoServerError: bad auth : Authentication failed. (Atlas user / special characters in password) Atlas rejected the username/password in the connection string.
BSONObj size is invalid / exceeds maximum document size (16MB) MongoServerError: BSONObj size: 17825792 (0x1100000) is invalid. Size must be between 0 and 16793600(16MB) A single document (or an aggregation result row) grew past MongoDB's 16 MB limit.
NamespaceNotFound: ns not found MongoServerError: ns not found (NamespaceNotFound) — dropping/renaming/collStats on a missing collection A command referenced a collection (namespace) that doesn't exist.
NoSuchTransaction: Transaction was aborted or expired MongoServerError: Transaction 1 has been aborted / NoSuchTransaction: transaction has expired (transactionLifetimeLimitSeconds) A transaction ran longer than the allowed lifetime (60 s default) or was aborted, so later operations fail.
Query failed: $or / $in / projection errors (BadValue) MongoServerError: Unknown modifier / unknown top level operator: $foo / Cannot use $in with a non-array The query or update used an invalid operator or argument type.
WriteConflict: Write conflict during plan execution MongoServerError: WriteConflict error: this operation conflicted with another operation. Please retry your operation or multi-document transaction Two operations tried to modify the same document at once; one was aborted with a transient error.
MongoDB TLS: SSL routines / certificate error MongoServerSelectionError: C0A8:error:0A000438:SSL routines:ssl3_read_bytes:tlsv1 alert internal error (Atlas) / self-signed certificate The TLS handshake with MongoDB failed — certificate trust, TLS version, or a proxy/IP block.
No primary found in replica set / ReplicaSetNoPrimary MongoServerSelectionError: Server selection timed out after 30000 ms — topology type ReplicaSetNoPrimary The driver sees the replica set members but none is a primary (election failing or members unreachable).
NotImplementedError: Collection objects do not implement truth value testing PyMongo: NotImplementedError: Database objects do not implement truth value testing or bool(). Please compare with None instead: database is not None You used a Database/Collection object in an `if` (`if db:`), which PyMongo forbids.
BSONError: input must be a 24 character hex string BSONTypeError: Argument passed in must be a string of 12 bytes or a string of 24 hex characters `new ObjectId(value)` received a value that isn't a valid 24-hex id.
MONGO_INITDB_ROOT_USERNAME ignored (data volume exists) Docker: MongoServerError: Authentication failed — after changing MONGO_INITDB_ROOT_PASSWORD The official Mongo image creates the root user only on the very first start with an empty data directory; cha…
mongod: Too many open files (ulimit warning) MongoDB: WARNING: soft rlimits too low. Number of files is 1024, should be at least 64000 / Too many open files The OS file-descriptor limit for `mongod` is too low, causing connection or file errors under load.
mongodump: Failed: not authorized / authentication failed mongodump: Failed: error getting database collections: not authorized on db to execute command { listCollections } `mongodump` connected but the user isn't allowed to read the data, or authentication didn't happen.
MongoParseError: options usenewurlparser / useunifiedtopology not supported MongoParseError: option usenewurlparser is not supported Old connection options removed in Mongoose 6 / driver 4 are still passed to `mongoose.connect`.
mongorestore: failed to restore (duplicate key / BSON / version) mongorestore: Failed: db.coll: error restoring from dump: E11000 duplicate key error / unsupported BSON version `mongorestore` couldn't load some documents — they already exist, indexes conflict, or the dump/server versio…
NamespaceExists: Collection already exists MongoServerError: Collection db.users already exists (NamespaceExists) `createCollection` (or an index/rename) targeted a name that is already in use.
CursorNotFound: cursor id not found MongoServerError: cursor id 1234567890 not found (CursorNotFound) A cursor you were iterating timed out or was killed on the server, so the next batch fails.
Executor error: Sort exceeded memory limit (find().sort) MongoServerError: Executor error during find command :: caused by :: Sort exceeded memory limit of 104857600 bytes, but did not opt in to external sorting A `find().sort()` without a supporting index had to sort too much data in memory.
createIndex failed: unique index with duplicates MongoServerError: Index build failed: E11000 duplicate key error collection: db.users index: email_1 dup key You tried to build a unique index but existing documents already contain duplicate values.
NotWritablePrimary: not primary and secondaryOk=false MongoServerError: not primary and secondaryOk=false / NotWritablePrimary: not master A write (or read without secondary preference) hit a secondary — the primary changed or you connected directl…
MongoDB Atlas: connection timed out — IP not whitelisted MongoServerSelectionError: Could not connect to any servers in your MongoDB Atlas cluster. One common reason is that you're trying to access the database from an IP that isn't whitelisted Atlas rejects connections from IP addresses that aren't in the project's Network Access list.
pymongo.errors.BulkWriteError: batch op errors occurred PyMongo: pymongo.errors.BulkWriteError: batch op errors occurred A bulk insert/update had one or more failed operations; details are in `e.details`.
pymongo.errors.ServerSelectionTimeoutError PyMongo: pymongo.errors.ServerSelectionTimeoutError: localhost:27017: [Errno 111] Connection refused, Timeout: 30s PyMongo couldn't find a usable MongoDB server within the selection timeout.
WARNING: /sys/kernel/mm/transparent_hugepage/enabled is 'always' MongoDB startup: WARNING: /sys/kernel/mm/transparent_hugepage/enabled is 'always'. We suggest setting it to 'never' Transparent Huge Pages are enabled, which can hurt MongoDB performance (latency spikes).
Mongoose: strictQuery will be switched back to false Mongoose: [MONGOOSE] DeprecationWarning: Mongoose: the strictQuery option will be switched back to false by default in Mongoose 7 A deprecation warning about how unknown fields in query filters are handled.
CastError: Cast to Date/Number/Boolean failed Mongoose: CastError: Cast to date failed for value "abc" (type string) at path "createdAt" A value couldn't be converted to the schema type at that path (date, number, boolean).
The uri parameter to openUri() must be a string, got "undefined" MongooseError: The `uri` parameter to `openUri()` must be a string, got "undefined". Make sure the first parameter to `mongoose.connect()` is a string `mongoose.connect()` received `undefined` instead of a connection string — the environment variable wasn't lo…
Index key too large to index MongoServerError: Index key too large to index (key size exceeds 1024 bytes) / pre-4.2 behaviour A document has an indexed field whose value is too large for the index (limit 1024 bytes before MongoDB 4.2).