Home > Database > MongoDB > body text

Connect MongoDB with NodeJS

PHPz
Release: 2023-08-23 18:21:02
forward
1683 people have browsed it

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])
Copy after login

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
Copy after login
  • 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
Copy after login
  • 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
Copy after login

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");
})
Copy after login

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.
Copy after login

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

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template