本教程将带你了解如何在 Node.js 应用中使用 MongoDB 数据库。我们将一步一步地介绍如何连接数据库、创建集合、插入文档、查询数据等。

连接 MongoDB

首先,你需要确保 MongoDB 服务器已经运行。然后,使用以下代码连接到 MongoDB 数据库:

const MongoClient = require('mongodb').MongoClient;

const url = 'mongodb://localhost:27017';

MongoClient.connect(url, { useNewUrlParser: true, useUnifiedTopology: true }, (err, db) => {
  if (err) throw err;
  console.log('数据库连接成功');
  const dbo = db.db('mydb');
  // ...
  db.close();
});

创建集合

接下来,我们可以创建一个集合:

dbo.createCollection("customers", (err, res) => {
  if (err) throw err;
  console.log("集合创建成功");
});

插入文档

现在,我们可以向集合中插入文档:

const customer = { name: "John Doe", email: "john.doe@example.com" };
dbo.collection("customers").insertOne(customer, (err, res) => {
  if (err) throw err;
  console.log("文档插入成功");
});

查询数据

要查询数据,可以使用以下代码:

dbo.collection("customers").find({ name: "John Doe" }).toArray((err, result) => {
  if (err) throw err;
  console.log(result);
});

扩展阅读

想要了解更多关于 Node.js 和 MongoDB 的内容,可以阅读我们的Node.js MongoDB 高级教程

MongoDB