{"record":{"id":"b6de2e7fcb3b29e7","repo":"Automattic/mongoose","slug":"cannot-call-this-name-i-before-initial-c","errorCode":null,"errorMessage":"Cannot call `${this.name}.${i}()` before initial connection is complete if `bufferCommands = false`. Make sure you `await mongoose.connect()` if you have `bufferCommands = false`.","messagePattern":"Cannot call `(.+?)\\.(.+?)\\(\\)` before initial connection is complete if `bufferCommands = false`\\. Make sure you `await mongoose\\.connect\\(\\)` if you have `bufferCommands = false`\\.","errorType":"exception","errorClass":"MongooseError","httpStatus":null,"severity":"error","filePath":"lib/drivers/node-mongodb-native/collection.js","lineNumber":192,"sourceCode":"        const shell = debug.shell == null ? false : debug.shell;\n        const timestamp = debug.timestamp == null ? false : debug.timestamp;\n        this.$print(_this.name, i, args, color, shell, timestamp);\n      }\n    }\n\n    if (hasOperationListeners) {\n      if (argsArray == null) {\n        argsArray = Array.from(args);\n      }\n      this.conn.emit('operation-start', { _id: opId, modelName: _this.modelName, collectionName: this.name, method: i, params: argsArray });\n    }\n\n    try {\n      if (collection == null) {\n        const message = 'Cannot call `' + this.name + '.' + i + '()` before initial connection ' +\n          'is complete if `bufferCommands = false`. Make sure you `await mongoose.connect()` if ' +\n          'you have `bufferCommands = false`.';\n        throw new MongooseError(message);\n      }\n\n      const ret = collection[i].apply(collection, args);\n      if (typeof ret?.then === 'function') {\n        return ret.then(\n          result => {\n            if (timeout != null) {\n              clearTimeout(timeout);\n            }\n            if (hasOperationListeners) {\n              this.conn.emit('operation-end', { _id: opId, modelName: _this.modelName, collectionName: this.name, method: i, result });\n            }\n            return result;\n          },\n          error => {\n            if (timeout != null) {\n              clearTimeout(timeout);\n            }","sourceCodeStart":174,"sourceCodeEnd":210,"githubUrl":"https://github.com/Automattic/mongoose/blob/49cdab01366679723b487ecb754b38570f783289/lib/drivers/node-mongodb-native/collection.js#L174-L210","documentation":"With bufferCommands: false, Mongoose does not queue collection operations while the connection is still connecting. The native collection wrapper throws this MongooseError when any collection method (findOne, insertOne, ...) runs before the underlying collection object exists, i.e. before mongoose.connect()/createConnection() completed. With buffering on (the default) such calls would wait silently; disabling it trades silence for early, explicit failure.","triggerScenarios":"mongoose.connect(uri, { bufferCommands: false }) or mongoose.set('bufferCommands', false), then calling Model.findOne(), Model.create(), doc.save(), etc. before the connect promise resolves - e.g. queries fired at module load or in a request handler hit during startup.","commonSituations":"Fire-and-forget connect() without await; serverless handlers running before an awaited connect; tests issuing queries in hooks without awaiting connection setup; startup races after enabling fail-fast buffering.","solutions":["Await the connection before any query: await mongoose.connect(uri) at process entry, or await mongoose.connection.asPromise().","Start the HTTP listener and job workers only after the connect promise resolves.","If startup order cannot be guaranteed, remove bufferCommands: false so commands buffer again.","In tests, await a shared connection promise in the top-level before() hook."],"exampleFix":"// before\nmongoose.connect(uri, { bufferCommands: false }); // not awaited\napp.get('/users', async (req, res) => {\n  const users = await User.find(); // throws: connection not ready\n  res.json(users);\n});\n\n// after\nawait mongoose.connect(uri, { bufferCommands: false });\napp.get('/users', async (req, res) => {\n  const users = await User.find();\n  res.json(users);\n});","handlingStrategy":"validation","validationCode":"async function ensureConnected() {\n  if (mongoose.connection.readyState !== 1) {\n    await mongoose.connection.asPromise();\n  }\n}\nawait ensureConnected();\nconst users = await User.find();","typeGuard":"function isConnected(conn = mongoose.connection) {\n  return conn.readyState === 1; // 1 === STATES.connected\n}","tryCatchPattern":"try {\n  await User.find();\n} catch (err) {\n  if (err instanceof mongoose.MongooseError && err.message.includes('before initial connection')) {\n    await mongoose.connection.asPromise();\n    return User.find(); // single retry after connection completes\n  }\n  throw err;\n}","preventionTips":["Always await mongoose.connect() (or connection.asPromise()) in the process entrypoint before starting servers or workers.","Export a single connect() promise module that every entrypoint (API, jobs, tests) awaits.","Keep buffering enabled in environments with unpredictable init order; disable it only where startup is strictly sequenced and fail-fast is wanted."],"tags":["mongoose","connection","buffercommands","startup","race-condition"],"backgroundTag":"database-not-connected","analyzedSha":"49cdab01366679723b487ecb754b38570f783289","analyzedAt":"2026-08-21T22:54:00.882Z","schemaVersion":2},"datasetVersion":"2026-08-21T23:17:16.201Z"}