Home > other >  Possible to have Mongoose return a connection?
Possible to have Mongoose return a connection?

Time:10-28

When using eg. MySQL, one open a connection fx:

const c = await mysql.createConnection({
     host: 'localhost',
     user: 'x',
     password: 'x',
     database: 'x',
     Promise: bluebird,
  });

and then perform actions on the connection c like so

const [rows, fields] = await c.execute(q);

but with Mongoose mongoose.connect() doesn't return a connection. it is nice not that it "just works", but I really would prefer the MySQL approach where it is explicitly written which database connection that is used.

Is that possible with Mongoose?

CodePudding user response:

You can use the mongoose.createConnection() function takes the same arguments as mongoose.connect() and returns a new connection.

const conn = mongoose.createConnection('mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]', options);

This connection object is then used to create and retrieve models. Models are always scoped to a single connection.

const UserModel = conn.model('User', userSchema);

https://mongoosejs.com/docs/connections.html#multiple_connections

CodePudding user response:

Once you have opened a connection with mongoose.connect(), you can then perform actions with mongoose.connection:

mongoose.connect(connectionString)
const c = mongoose.connection
  • Related