贝利信息

将MongoDB与NodeJS连接

日期:2023-08-23 00:00 / 作者:PHPz

mongodb.connect介绍

这个方法用于将Mongo DB服务器与我们的Node应用程序连接起来。这是MongoDB模块中的一个异步方法。

语法

mongodb.connect(path[, callback])

参数

安装Mongo-DB

在尝试将应用程序与Nodejs连接之前,我们首先需要设置MongoDB服务器。

npm install mongodb –save
mongod --dbpath=data --bind_ip 127.0.0.1
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");
})

输出

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.