Node.js Connect to MongoDB
Node.js Connect to MongoDB – In this Node.js Tutorial, we shall learn to connect to MongoDB from Node.js Application.
Prerequisites
- Make sure MongoDB is installed. If not, install MongoDB.
Step by step guide
To connect to MongoDB from Node.js Application, following is a step by step guide.
- Start MongoDB service. Run the following command to start MongoDB Service sudo service mongod start
- Install mongodb package using npm (if not installed already). arjun@nodejs:~/workspace/nodejs/mongodb$ npm install mongodbnpm WARN saveError ENOENT: no such file or directory, open '/home/arjun/workspace/nodejs/package.json'npm WARN enoent ENOENT: no such file or directory, open '/home/arjun/workspace/nodejs/package.json'npm WARN nodejs No descriptionnpm WARN nodejs No repository field.npm WARN nodejs No README datanpm WARN nodejs No license field.+ mongodb@2.2.33added 9 packages in 9.416s
- Prepare the url. A simple hack to know the base url of MongoDB Service is to Open a Terminal and run Mongo Shell. While the Mongo Shell starts up, it echoes back the base url of MongoDB.arjun@nodejs:~$ mongoMongoDB shell version v3.4.9connecting to: mongodb://127.0.0.1:27017MongoDB server version: 3.4.9Server has startup warnings:2017-10-29T18:15:36.110+0530 I STORAGE [initandlisten]mongodb://127.0.0.1:27017
- With the help of mongodb package, create a MongoClient and connect to the url.
Example Program – Node.js Connect to MongoDB
Following is an Example Node.js program to make a Node.js MongoDB Connection.
// URL at which MongoDB service is running var url = "mongodb://localhost:27017"; // A Client to MongoDB var MongoClient = require('mongodb').MongoClient; // Make a connection to MongoDB Service MongoClient.connect(url, function(err, db) { if (err) throw err; console.log("Connected to MongoDB!"); db.close(); }); |
arjun@java:~/workspace/nodejs/mongodb$ node node-js-mongodb-connection.js Connected to MongoDB! |
Conclusion :
In this Node.js MongoDB – Node.js Connect to MongoDB, we have learnt to find the url of the MongoDB Service and connect to the service from Node.js using MongoClient’s connect method, demonstrated by an Example program.