Automattic/mongoose · error · MongooseError
Cannot call `${this.name}.${i}()` before initial connection
Error message
Cannot call `${this.name}.${i}()` before initial connection is complete if `bufferCommands = false`. Make sure you `await mongoose.connect()` if you have `bufferCommands = false`. What it means
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.
Source
Thrown at lib/drivers/node-mongodb-native/collection.js:192
const shell = debug.shell == null ? false : debug.shell;
const timestamp = debug.timestamp == null ? false : debug.timestamp;
this.$print(_this.name, i, args, color, shell, timestamp);
}
}
if (hasOperationListeners) {
if (argsArray == null) {
argsArray = Array.from(args);
}
this.conn.emit('operation-start', { _id: opId, modelName: _this.modelName, collectionName: this.name, method: i, params: argsArray });
}
try {
if (collection == null) {
const message = 'Cannot call `' + this.name + '.' + i + '()` before initial connection ' +
'is complete if `bufferCommands = false`. Make sure you `await mongoose.connect()` if ' +
'you have `bufferCommands = false`.';
throw new MongooseError(message);
}
const ret = collection[i].apply(collection, args);
if (typeof ret?.then === 'function') {
return ret.then(
result => {
if (timeout != null) {
clearTimeout(timeout);
}
if (hasOperationListeners) {
this.conn.emit('operation-end', { _id: opId, modelName: _this.modelName, collectionName: this.name, method: i, result });
}
return result;
},
error => {
if (timeout != null) {
clearTimeout(timeout);
}View on GitHub (pinned to 49cdab0136)
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.
Example fix
// before
mongoose.connect(uri, { bufferCommands: false }); // not awaited
app.get('/users', async (req, res) => {
const users = await User.find(); // throws: connection not ready
res.json(users);
});
// after
await mongoose.connect(uri, { bufferCommands: false });
app.get('/users', async (req, res) => {
const users = await User.find();
res.json(users);
}); Defensive patterns
Strategy: validation
Validate before calling
async function ensureConnected() {
if (mongoose.connection.readyState !== 1) {
await mongoose.connection.asPromise();
}
}
await ensureConnected();
const users = await User.find(); Type guard
function isConnected(conn = mongoose.connection) {
return conn.readyState === 1; // 1 === STATES.connected
} Try / catch
try {
await User.find();
} catch (err) {
if (err instanceof mongoose.MongooseError && err.message.includes('before initial connection')) {
await mongoose.connection.asPromise();
return User.find(); // single retry after connection completes
}
throw err;
} Prevention
- 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.
When it happens
Trigger: 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.
Common situations: 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.
Related errors
- Connection operation buffering timed out after ${bufferTimeo
- Connection#createClient not implemented by driver
- No connections to database "${name}" found
- The `uri` parameter to `openUri()` must be a string, got "${
- Connection has been closed and destroyed, and cannot be used
AI-assisted analysis of Automattic/mongoose@49cdab0136 (2026-08-21).
Data as JSON: /api/errors/b6de2e7fcb3b29e7.
Report an issue: GitHub.