Node 及 MongoDB - 连接数据库



Node mongodb 提供了 **mongoClient** 对象,该对象用于使用 connect() 方法连接数据库连接。此函数采用多个参数,并提供 db 对象执行数据库操作。

语法

// MongoDBClient
const client = new MongoClient(url, { useUnifiedTopology: true });
// make a connection to the database
client.connect();

你可以随时使用另一个连接对象函数 **close()** 从 MongoDB 数据库断开连接。

语法

client.close()

示例

尝试以下示例以连接到 MongoDB 服务器 -

将以下示例复制粘贴为 mongodb_example.js -

const MongoClient = require('mongodb').MongoClient;
// Prepare URL
const url = "mongodb://:27017/";
// make a connection to the database
MongoClient.connect(url, function(error, client) {
   if (error) throw error;
   console.log("Connected!");
   // close the connection
   client.close();
});

输出

使用 Node 执行 mysql_example.js 脚本,并验证输出。

node mongodb_example.js
Connected!
广告
© . All rights reserved.