Home >Database >MongoDB >Connect MongoDB with NodeJS

Connect MongoDB with NodeJS

PHPz
PHPzforward
2023-08-23 18:21:021741browse

Connect MongoDB with NodeJS

mongodb.connect introduction

This method is used to connect the Mongo DB server with our Node application. This is an asynchronous method in the MongoDB module.

Syntax

mongodb.connect(path[, callback])

Parameters

  • •path – The server path and port where the MongoDB server is actually running.

  • •callback – This function will provide a callback if any error occurs.

Installing Mongo-DB

Before trying to connect the application with Nodejs, we first need to set up the MongoDB server.

  • Use the following query to install mongoDB from npm.

npm install mongodb –save
  • Run the following command to set up your mongoDB on a specific local server. This will help establish connection with MongoDB.

mongod --dbpath=data --bind_ip 127.0.0.1
  • Create a MongodbConnect.js file and copy-paste the following code snippet into the 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.

The above is the detailed content of Connect MongoDB with NodeJS. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete