Mongoose: How to connect to two databases in a single node server?

Created on 10 Oct 2019  路  2Comments  路  Source: Automattic/mongoose

I have a question about mongoose.

In my Nodejs server I need to connect to two different databases, let say "localhost:27017/db1" and "localhost:27017/db2".

Inside a rest Api I need to insert a document into a collection (Collectiondb1) of db1, and another document (different from the previous one) into a collection (Collectiondb2) of db2.

The code is:

Collectiondb1.create({email:'hello'}).then(...).catch(....);
Collectiondb2.create({test:'welcome'}).then(...).catch(....);

How can I do that?
If I try this I get both documents inside the same database (the last one).
I also tried to export instances of mongoose without success.

Do you have any suggestions?

Most helpful comment

const conn = mongoose.createConnection('mongodb://localhost:27017/db1');
const conn2 = mongoose.createConnection('mongodb://localhost:27017/db2');
const userSchema = new mongoose.Schema({})
const blogSchema = new mongoose.Schema({})
const User = conn.model('User', userSchema);
const Blog = conn2.model('Item', blogSchema);

This could be the thing you are looking for.

All 2 comments

const conn = mongoose.createConnection('mongodb://localhost:27017/db1');
const conn2 = mongoose.createConnection('mongodb://localhost:27017/db2');
const userSchema = new mongoose.Schema({})
const blogSchema = new mongoose.Schema({})
const User = conn.model('User', userSchema);
const Blog = conn2.model('Item', blogSchema);

This could be the thing you are looking for.

@shajanjp 's suggestion is correct. Please see multiple connections docs for more info.

Was this page helpful?
0 / 5 - 0 ratings