{"record":{"id":"bb796a2316eef05d","repo":"Automattic/mongoose","slug":"useconnection-requires-a-mongoose-connection","errorCode":null,"errorMessage":"`useConnection()` requires a Mongoose connection.","messagePattern":"`useConnection\\(\\)` requires a Mongoose connection\\.","errorType":"exception","errorClass":"MongooseError","httpStatus":null,"severity":"error","filePath":"lib/model.js","lineNumber":199,"sourceCode":" *\n *     UserModel.connection === mongoose.connection; // false\n *     UserModel.connection === conn2; // true\n *\n *     conn2.model('User') === UserModel; // true\n *     mongoose.model('User'); // Throws 'MissingSchemaError'\n *\n * Note: `useConnection()` does **not** apply any [connection-level plugins](https://mongoosejs.com/docs/api/connection.html#Connection.prototype.plugin()) from the new connection.\n * If you use `useConnection()` to switch a model's connection, the model will still have the old connection's plugins.\n *\n * @function useConnection\n * @param {Connection} connection The new connection to use\n * @return {Model} this\n * @api public\n */\n\nModel.useConnection = function useConnection(connection) {\n  if (typeof connection?.model !== 'function' || typeof connection.collection !== 'function' || typeof connection.base?.version !== 'string') {\n    throw new MongooseError('`useConnection()` requires a Mongoose connection.');\n  }\n  if (this.db?.base?.version && this.db?.base?.version !== connection.base?.version) {\n    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}).`);\n  }\n  if (this.db) {\n    delete this.db.models[this.modelName];\n    delete this.prototype.db;\n    delete this.prototype[modelDbSymbol];\n    delete this.prototype.collection;\n    delete this.prototype.$collection;\n    delete this.prototype[modelCollectionSymbol];\n  }\n\n  this.db = connection;\n  const collection = connection.collection(this.collection.collectionName, connection.options);\n  this.prototype.collection = collection;\n  this.prototype.$collection = collection;\n  this.prototype[modelCollectionSymbol] = collection;","sourceCodeStart":181,"sourceCodeEnd":217,"githubUrl":"https://github.com/Automattic/mongoose/blob/49cdab01366679723b487ecb754b38570f783289/lib/model.js#L181-L217","documentation":"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.","triggerScenarios":"UserModel.useConnection(mongoose.connection.db) (the Node driver Db), .useConnection(client) (MongoClient), .useConnection(SomeModel), or a hand-rolled mock connection in tests.","commonSituations":"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.","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"],"exampleFix":"// before\nconst client = new MongoClient(uri);\nawait client.connect();\nUserModel.useConnection(client.db('app')); // db is not a Mongoose connection\n\n// after\nconst conn = await mongoose.createConnection(uri).asPromise();\nUserModel.useConnection(conn);","handlingStrategy":"type-guard","validationCode":"// Verify the argument is a Mongoose connection before switching\nfunction isMongooseConnection(conn) {\n  return typeof conn?.model === 'function'\n    && typeof conn.collection === 'function'\n    && typeof conn?.base?.version === 'string';\n}\nif (isMongooseConnection(conn)) UserModel.useConnection(conn);","typeGuard":"function isMongooseConnection(conn) {\n  return !!conn && typeof conn.model === 'function' && typeof conn.collection === 'function' && typeof conn.base?.version === 'string';\n}","tryCatchPattern":"try {\n  model.useConnection(conn);\n} catch (err) {\n  if (err instanceof mongoose.MongooseError && /requires a Mongoose connection/.test(err.message)) {\n    // resolve the right object (mongoose.connection or createConnection result) and retry\n  } else throw err;\n}","preventionTips":["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"],"tags":["mongoose","connection","useconnection","type-mismatch"],"backgroundTag":"connection-type-mismatch","analyzedSha":"49cdab01366679723b487ecb754b38570f783289","analyzedAt":"2026-08-21T22:54:00.882Z","schemaVersion":2},"datasetVersion":"2026-08-21T23:17:16.201Z"}