mongodb.connect()method是Node.js的MongoDB模块的方法, 该模块用于将MongoDB数据库与我们的Node.js应用程序连接。这是MongoDB模块的异步方法。
语法如下:
mongodb.connect(path, callbackfunction) 参数:此方法接受上面提到并在下面描述的两个参数:
- path/URL:在特定端口号上运行的MongoDB服务器的服务器的路径。
- callbackfunction:如果连接成功, 它将返回err或mongodb数据库实例以进行进一步操作。
安装模块:
npm install mongodb --save 项目结构:
在特定IP上运行服务器的命令:
mongod --dbpath=data --bind_ip 127.0.0.1
文件名index.js
JavaScript
// Module calling const MongoClient = require( "mongodb" ); // Server path const url = 'mongodb://localhost:27017/' ; // Name of the database const dbname = "conFusion" ; MongoClient.connect(url, (err, client)=>{ if (!err) { console.log( "successful connection with the server" ); } else console.log( "Error in the connectivity" ); }) 运行命令:
node index.js 输出如下:
node index.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
srcmini
评论前必须登录!
注册