通过 NodeJS 连接 MongoDB
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
示例
// Calling the required MongoDB module.
const MongoClient = require("mongodb");
// Server path
const url = 'mongodb://: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.
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP