0
votes

My main file app.js is connected to userDB I want to add a second database postsDB


const mongoose = require("mongoose");


const app = express();


mongoose.set("useCreateIndex", true);
mongoose.set("useUnifiedTopology", true);

mongoose.connect("mongodb://localhost:27017/userDB", {useNewUrlParser: true});


1
Before posting a question I suggest searching through stack overflow in case it's been asked before. Here's a possible duplicate answer: stackoverflow.com/questions/32906467/…Alejandro

1 Answers

0
votes

If they are multiple databases in the same server, you can use useDb

const userDb = mongoose.connection.useDb('userDB');
const postsDb = mongoose.connection.useDb('postsDB');

Only do this if you have a good reason too though, the more standard approach would be to use multiple collections in the same database.

If the databases are in different servers, you'll need to use different connection pools entirely, and that is something mongoose does not support out-of-the-box. You can use the standard mongodb driver or split your app into different services, each with their own instance of mongoose, and own connection. This would be highly unusual within the same express application though.