- Node 及 MongoDB 教程
- Node 及 MongoDB - 主页
- Node 及 MongoDB - 概览
- Node 及 MongoDB - 环境设置
- Node 及 MongoDB 示例
- Node 及 MongoDB - 连接数据库
- Node 及 MongoDB - 显示数据库
- Node 及 MongoDB - 删除数据库
- Node 及 MongoDB - 创建集合
- Node 及 MongoDB - 删除集合
- Node 及 MongoDB - 显示集合
- Node 及 MongoDB - 插入文档
- Node 及 MongoDB - 选择文档
- Node 及 MongoDB - 更新文档
- Node 及 MongoDB - 删除文档
- Node 及 MongoDB - 嵌入式文档
- Node 及 MongoDB - 限制记录
- Node 及 MongoDB - 排序记录
- Node 及 MongoDB 有用的资源
- Node 及 MongoDB - 快速指南
- Node 及 MongoDB - 有用的资源
- Node 及 MongoDB - 讨论
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!
广告