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
Once you have opened a connection with
mongoose.connect()
, you can then perform actions withmongoose.connection
:You can use the
mongoose.createConnection()
function takes the same arguments asmongoose.connect()
and returns a new connection.This connection object is then used to create and retrieve models. Models are always scoped to a single connection.
https://mongoosejs.com/docs/connections.html#multiple_connections