This tutorial aims to show you how to open multiple MongoDB connections in Express.js application.
Now we want to create a package.json
file which will keep track of our dependencies information. To do that create a new file and put following content inside of it:
{
"name": "mongo-conn",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"scripts": {
"seed": "node seeder.js",
"dev": "nodemon index.js"
},
"dependencies": {
"express": "^4.17.1",
"faker": "^4.1.0",
"mongoose": "^5.9.7",
"nodemon": "^2.0.2"
}
}
Let's create a new file and call it index.js
. This file will holds our main server code. Put the following content inside index.js
file:
const express = require('express');
const {userModel, todoModel} = require('./models');
const app = express();
app.get('/users', async (req, res) => {
const users = await userModel.find({});
res.json(users);
});
app.get('/todos', async (req, res) => {
const todos = await todoModel.find({});
res.json(todos);
});
const port = 3000;
app.listen(port, () => console.log(`App listening at http://localhost:${port}`));
Now we will create a new file and call it connections.js
and put following content inside of it:
const mongoose = require('mongoose');
function makeNewConnection(uri) {
const db = mongoose.createConnection(uri, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
db.on('error', function (error) {
console.log(`MongoDB :: connection ${this.name} ${JSON.stringify(error)}`);
db.close().catch(() => console.log(`MongoDB :: failed to close connection ${this.name}`));
});
db.on('connected', function () {
mongoose.set('debug', function (col, method, query, doc) {
console.log(`MongoDB :: ${this.conn.name} ${col}.${method}(${JSON.stringify(query)},${JSON.stringify(doc)})`);
});
console.log(`MongoDB :: connected ${this.name}`);
});
db.on('disconnected', function () {
console.log(`MongoDB :: disconnected ${this.name}`);
});
return db;
}
const userConnection = makeNewConnection('mongodb://127.0.0.1:27017/user');
const todoConnection = makeNewConnection('mongodb://127.0.0.1:27017/todo');
module.exports = {
userConnection,
todoConnection,
};
Now lets create another file and call it models.js
and put following content inside of it:
const mongoose = require('mongoose');
const {userConnection, todoConnection} = require('./connections');
const userSchema = new mongoose.Schema({
name: String,
isActive: Boolean,
}, {
versionKey: false,
timestamps: true,
});
const todoSchema = new mongoose.Schema({
title: String,
completed: Boolean,
}, {
versionKey: false,
timestamps: true,
});
const userModel = userConnection.model('User', userSchema);
const todoModel = todoConnection.model('Todo', todoSchema);
module.exports = {
userModel,
todoModel,
};
Now lets create another file and name it seeder.js
and put following content inside of it:
const faker = require('faker');
const {userModel, todoModel} = require('./models');
const {userConnection, todoConnection} = require('./connections');
async function seed() {
for (let i = 0; i< 10; i++) {
await userModel.create({
name: faker.name.findName(),
isActive: faker.random.boolean(),
});
}
for (let i = 0; i < 10; i++) {
await todoModel.create({
title: faker.lorem.words(3),
completed: faker.random.boolean(),
});
}
}
seed().then(() => {
userConnection.close();
todoConnection.close();
});
Now open your terminal and seed your database with following command:
yarn seed
Lets start the application by running following command inside your terminal:
yarn dev
Now open the following link inside your browser:
http://localhost:3000/users
You can find the complete source code for this application on my GitHub profile:
Top comments (9)
Nice!
Is there anyway await the multiple DB connections before the server start listen http traffic? I never had founded a nice way to do that : (
To do that you have to import the file which contains the MongoDB connection code into main server file. Please have a look at the following code:
Put following code inside
connection.js
file:Now create another file and call it
index.js
and put following code inside of it:Thanks for your quick reply! I will try your suggestion
Thanks for your article, it helped me.
amazing
the best solution
Hi, I am working with node + typescript. This approach doesn't seems to work with ts environment.
@vigneshncc can you share your source code
Hello Zeeshan, Thanks for your code snippet. I took yours as a reference and I ended up changing it accordingly which suits for typescript. I made it very simple for now to work and that is why I haven't added the types fully.
The below code block works fine, except the commented one. All 'this' inside the functions are throwing error and would be great if you help me where I am doing wrong.
It's quite old question, but this may help someone in the future: check if your
process.env
variables aren'tundefined
. To fix this, you can movedotenv.config();
toconnections.js
file and use in beforemakeNewConnection(...)
function.