- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Connecting MongoDB with NodeJS
Introduction to mongodb.connect
This method is used to connect the Mongo DB server with our Node application. This is an asynchronous method from MongoDB module.
Syntax
mongodb.connect(path[, callback])
Parameters
•path – The server path where the MongoDB server is actually running along with its port.
•callback – This function will give a callback if any error occurs.
Installing Mongo-DB
Before proceeding to try connect your application with Nodejs, we need to setup our MongoDB server first.
Use the following query to install mongoDB from npm.
npm install mongodb –save
Run the following command to set up your mongoDB on the specific localhost server. This will help in creating connection with the MongoDB.
mongod --dbpath=data --bind_ip 127.0.0.1
Create a MongodbConnect.js and copy-paste the following code snippet into that file.
Now, run the following command to run the code snippet.
node MongodbConnect.js
Example
// Calling the required MongoDB module. const MongoClient = require("mongodb"); // Server path const url = 'mongodb://localhost:27017/'; // Name of the database const dbname = "Employee"; MongoClient.connect(url, (err,client)=>{ if(!err) { console.log("successful connection with the server"); } else console.log("Error in the connectivity"); })
Output
C:\Users\tutorialsPoint\> node MongodbConnect.js (node:7016) DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor. (Use `node --trace-deprecation ...` to show where the warning was created) successful connection with the server.
- Related Articles
- Image Processing with NodeJS JIMP
- Connecting SAP SOAP WebService with Android application
- Connecting to a MySQL database with Java
- Connecting Cities With Minimum Cost in Python\n
- Connecting system with SAP system using a Web Service
- Difference between NodeJS and AngularJS
- Introduction to ensureFileSync() in NodeJS
- Introduction to Sequelize in NodeJS
- Difference between NodeJS and ReactJS
- Difference between JavaScript and NodeJS
- Difference between NodeJS and JavaScript
- Async Copy in fs-extra - NodeJS
- Deleting records in MySQL using Nodejs
- Difference between process.cwd & _ _dirname in NodeJS
- Dropping a MySQL Table using NodeJS

Advertisements