English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

NodeJS Basic Tutorial

NodeJS Express.js

NodeJS Buffer&URL;

NodeJS MySql

NodeJS MongoDB

NodeJS File(FS)

NodeJS Others

Node.js Connect to MongoDB

Node.js connection to MongoDB –In this Node.js tutorial, we will learn how to connect to MongoDB from a Node.js application.

Prerequisites

Ensure that MongoDB is installed. If not, please install MongoDB.

Step-by-step guide

To connect to MongoDB from a Node.js application, please follow the following step-by-step guide.

Start the MongoDB service. Run the following command to start the MongoDB service

sudo service mongod start

 Install the MongoDB package using npm (if not already installed).

arjun@nodejs:~/workspace/nodejs/mongodb$ npm install mongodb
npm 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 description
npm WARN nodejs No repository field.
npm WARN nodejs No README data
npm WARN nodejs No license field.
 
+ [email protected]
added 9 packages in 9.416s

Prepare the URL. To understand the basic URL of the MongoDB service, a simple trick is to open the terminal and run Mongo Shell.
Terminal - Mongo Shell

arjun@nodejs:~$ mongo
MongoDB shell version v3.4.9
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.4.9
Server has startup warnings: 
2017-10-29T18:15:36.110+0530 I STORAGE [initandlisten]

When the Mongo Shell starts, it echoes the basic URL of MongoDB.

mongodb://127.0.0.1:27017

With the mongodb package, create MongoClient and connect to the url.

Example Program – Node.js Connect to MongoDB

The following is an example Node.js program to establish a connection to Node.js MongoDB.

// URL for Running MongoDB Service
var url = "mongodb://localhost:27017"; 
 
// MongoDB Customers
var MongoClient = require('mongodb').MongoClient; 
 
// Connect to MongoDB Service
MongoClient.connect(url, function(err, db) { 
  if (err) throw err; 
  console.log("Connected to MongoDB!"); 
  db.close(); 
 });

Output Result

arjun@java:~/workspace/nodejs/mongodb$ node node-js-mongodb-connection.js 
Connected to MongoDB!

Conclusion:

In this Node.js MongoDB – Connecting to MongoDB with Node.js, we learned how to find the MongoDB service URL and use the MongoClient's connect method to connect to the service from Node.js, as shown in the example program.