skip to Main Content

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?

2

Answers


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

    mongoose.connect(connectionString)
    const c = mongoose.connection
    
    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search