Multiple MongoDB Connections using NodeJS - Kevin Uriel Fonseca


Pretty late but this might help someone. The current answers assumes you are using the same file for your connections and models.

In real life, there is a high chance that you are splitting your models into different files. You can use something like this in your main file:

mongoose.connect('mongodb://localhost/default');const db = mongoose.connection;db.on('error', console.error.bind(console, 'connection error:'));db.once('open', () => {  console.log('connected');});

which is just how it is described in the docs. And then in your model files, do something like the following:

import mongoose, { Schema } from 'mongoose';const userInfoSchema = new Schema({  createdAt: {    type: Date,    required: true,    default: new Date(),  },  // ...other fields});const myDB = mongoose.connection.useDb('myDB');const UserInfo = myDB.model('userInfo', userInfoSchema);export default UserInfo;

Where myDB is your database name.

Sources:

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

https://stackoverflow.com/questions/19474712/mongoose-and-multiple-database-in-single-node-js-project

If you want to know more about Web Development with NodeJS, please take a look into this book:

Bye bye 🙂

SIDEBAR
FOOTER