将 MongoDB 与 NodeJS 连接
mongodb.connect介绍
此方法用于将MongoDB服务器与我们的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
示例
//调用所需的MongoDB模块。 const MongoClient = require("mongodb"); //服务器路径 const url = 'mongodb://localhost:27017/'; //数据库名称 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\nhooo\> 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.