Automattic/mongoose · error · MongooseError
`useConnection()` requires a Mongoose connection.
Error message
`useConnection()` requires a Mongoose connection.
What it means
Model.useConnection(connection) re-points a compiled model to a different connection. The argument must be a Mongoose Connection — the checks require callable model() and collection() plus a string base.version, which only Mongoose connections have. Passing the underlying driver Db, a MongoClient, a collection, or a stub throws this MongooseError before any model state is moved.
Source
Thrown at lib/model.js:199
*
* UserModel.connection === mongoose.connection; // false
* UserModel.connection === conn2; // true
*
* conn2.model('User') === UserModel; // true
* mongoose.model('User'); // Throws 'MissingSchemaError'
*
* Note: `useConnection()` does **not** apply any [connection-level plugins](https://mongoosejs.com/docs/api/connection.html#Connection.prototype.plugin()) from the new connection.
* If you use `useConnection()` to switch a model's connection, the model will still have the old connection's plugins.
*
* @function useConnection
* @param {Connection} connection The new connection to use
* @return {Model} this
* @api public
*/
Model.useConnection = function useConnection(connection) {
if (typeof connection?.model !== 'function' || typeof connection.collection !== 'function' || typeof connection.base?.version !== 'string') {
throw new MongooseError('`useConnection()` requires a Mongoose connection.');
}
if (this.db?.base?.version && this.db?.base?.version !== connection.base?.version) {
throw new MongooseError(`The connection passed to \`useConnection()\` has a different version of Mongoose (${connection.base?.version}) than the model you are using (${this.db?.base?.version}).`);
}
if (this.db) {
delete this.db.models[this.modelName];
delete this.prototype.db;
delete this.prototype[modelDbSymbol];
delete this.prototype.collection;
delete this.prototype.$collection;
delete this.prototype[modelCollectionSymbol];
}
this.db = connection;
const collection = connection.collection(this.collection.collectionName, connection.options);
this.prototype.collection = collection;
this.prototype.$collection = collection;
this.prototype[modelCollectionSymbol] = collection;View on GitHub (pinned to 49cdab0136)
Solutions
- Pass a Mongoose connection: model.useConnection(mongoose.connection) or the object returned by (await mongoose.createConnection(uri).asPromise())
- Use connection.db only for raw driver operations, never for useConnection
- In tests use a real or mongodb-memory-server connection instead of a partial stub
Example fix
// before
const client = new MongoClient(uri);
await client.connect();
UserModel.useConnection(client.db('app')); // db is not a Mongoose connection
// after
const conn = await mongoose.createConnection(uri).asPromise();
UserModel.useConnection(conn); Defensive patterns
Strategy: type-guard
Validate before calling
// Verify the argument is a Mongoose connection before switching
function isMongooseConnection(conn) {
return typeof conn?.model === 'function'
&& typeof conn.collection === 'function'
&& typeof conn?.base?.version === 'string';
}
if (isMongooseConnection(conn)) UserModel.useConnection(conn); Type guard
function isMongooseConnection(conn) {
return !!conn && typeof conn.model === 'function' && typeof conn.collection === 'function' && typeof conn.base?.version === 'string';
} Try / catch
try {
model.useConnection(conn);
} catch (err) {
if (err instanceof mongoose.MongooseError && /requires a Mongoose connection/.test(err.message)) {
// resolve the right object (mongoose.connection or createConnection result) and retry
} else throw err;
} Prevention
- Pass only connections produced by mongoose.connect/createConnection (or mongoose.connection)
- Keep driver objects (client, db, collection) out of Mongoose API calls
- Type the parameter as `import('mongoose').Connection` in TypeScript to catch this at compile time
When it happens
Trigger: UserModel.useConnection(mongoose.connection.db) (the Node driver Db), .useConnection(client) (MongoClient), .useConnection(SomeModel), or a hand-rolled mock connection in tests.
Common situations: Multi-tenant setups moving models between connections; mixing mongodb-driver objects with Mongoose connection objects; unit tests passing partial stubs; destructuring `const { connection }` from a client expecting Mongoose semantics.
Related errors
- "${value}" cannot be casted to a UUID
- Connection#createClient not implemented by driver
- Cannot call `${this.name}.${i}()` before initial connection
- No connections to database "${name}" found
- 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/bb796a2316eef05d.
Report an issue: GitHub.