MongoDB Node.js 数据库交互
Node.js 数据库交互
在本教程中,我们将使用 MongoDB Atlas 数据库。如果您还没有 MongoDB Atlas 账户,可以免费在 MongoDB Atlas 注册。
我们还将使用来自 聚合介绍 部分的示例数据加载的 "sample_mflix" 数据库。
MongoDB Node.js Driver 安装
要在 Node.js 中使用 MongoDB,您需要在 Node.js 项目中安装 mongodb
包。
在终端中使用以下命令安装 mongodb
包
npm install mongodb
现在我们可以使用此包连接到 MongoDB 数据库。
在项目目录中创建一个 index.js
文件。
index.js
const { MongoClient } = require('mongodb');
连接字符串
为了连接到我们的 MongoDB Atlas 数据库,我们需要从 Atlas 仪表盘获取连接字符串。
转到 **Database**,然后点击集群上的 **CONNECT** 按钮。
选择 **Connect your application**,然后复制您的连接字符串。
示例: mongodb+srv://<username>:<password>@<cluster.string>.mongodb.net/myFirstDatabase?retryWrites=true&w=majority
您需要将 <username>
、<password>
和 <cluster.string>
替换为您的 MongoDB Atlas 用户名、密码和集群字符串。
连接到 MongoDB
让我们添加到 index.js
文件中。
index.js
const { MongoClient } = require('mongodb');
const uri = "<Your Connection String>";
const client = new MongoClient(uri);
async function run() {
try {
await client.connect();
const db = client.db('sample_mflix');
const collection = db.collection('movies');
// Find the first document in the collection
const first = await collection.findOne();
console.log(first);
} finally {
// Close the database connection when finished or an error occurs
await client.close();
}
}
run().catch(console.error);
自己动手试一试 »
在终端中运行此文件。
node index.js
您应该会在控制台中看到第一个文档被记录下来。
CRUD & 文档聚合
就像我们使用 mongosh
一样,我们可以使用 MongoDB Node.js 语言驱动程序在数据库中创建、读取、更新、删除和聚合文档。
基于之前的示例,我们可以将 collection.findOne()
替换为 find()
、insertOne()
、insertMany()
、updateOne()
、updateMany()
、deleteOne()
、deleteMany()
或 aggregate()
。
尝试其中一些。