
mongodb.connect介绍
这个方法用于将Mongo DB服务器与我们的Node应用程序连接起来。这是MongoDB模块中的一个异步方法。
语法
mongodb.connect(path[, callback])
参数
•path – 实际运行MongoDB服务器的服务器路径和端口。
•callback – 如果发生任何错误,此函数将提供回调。
安装Mongo-DB
在尝试将应用程序与Nodejs连接之前,我们首先需要设置MongoDB服务器。
使用以下查询从npm安装mongoDB。
npm install mongodb –save
运行以下命令在特定的本地服务器上设置您的mongoDB。这将有助于与MongoDB建立连接。
mongod --dbpath=data --bind_ip 127.0.0.1
创建一个MongodbConnect.js文件,并将以下代码片段复制粘贴到该文件中。
现在,运行以下命令来运行代码片段。
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.










