将 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.热门推荐
1 训练狗狗基础
2 怎么训练狗狗笑
3 怎么训练狗狗卧下
4 上海狗狗训练基地
5 训练狗狗排便
6 狗狗基础训练
8 如何训练狗狗装死
9 狗狗站姿训练
10 狗狗训练用品
11 训练狗狗吧
12 狗狗要怎么训练
13 怎么训练狗狗玩球
14 训练狗狗唤回
15 狗狗训练躺下
16 狗狗训练指令
17 狗狗的训练技巧
18 狗狗不好训练