📌  相关文章
📜  使用 mongoose 从 mongodb 节点 js 获取数据 - Javascript (1)

📅  最后修改于: 2023-12-03 15:06:48.790000             🧑  作者: Mango

使用 Mongoose 从 MongoDB 节点 JS 获取数据

Mongoose 是一个 Node.js 的 MongoDB 驱动,它可以在 Node.js 中定义模型并与 MongoDB 数据库交互。使用 Mongoose,程序员可以方便地在 Node.js 应用程序中使用 MongoDB,而无需编写低级的数据库管理代码。

安装 Mongoose

首先,需要在项目中安装 Mongoose。可以使用 npm 命令进行安装:

npm install mongoose
连接 MongoDB

使用 Mongoose 连接 MongoDB,需要首先在 Node.js 代码中引入 mongoose 模块,并使用 connect() 方法连接到 MongoDB 数据库。以下是连接到本地 MongoDB 实例的示例:

const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test', {useNewUrlParser: true});
定义模型

Mongoose 允许开发人员定义数据模型,这些模型定义了文档结构和属性类型。以下是使用 Mongoose 定义数据模型的示例:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const userSchema = new Schema({
  name: { type: String, required: true },
  age: { type: Number, required: true },
  email: { type: String, required: true },
});

const User = mongoose.model('User', userSchema);

module.exports = User;

在上面的示例中,定义了一个名为 User 的数据模型,它有三个属性:name、age 和 email,每个属性都有一个类型定义,且所有属性都是必填的。

查询数据

使用 Mongoose 查询 MongoDB 数据库中的数据,需要基于定义好的数据模型来操作。以下是查询所有 User 文档的示例:

const User = require('./userModel');

User.find({}, (error, users) => {
  if (error) {
    console.log(error);
    return;
  }
  console.log(users);
});

在上面的示例中,使用 find() 方法查询所有 User 文档,并将查询结果作为参数传递给回调函数。如果查询发生错误,则回调函数会打印错误;否则,打印查询结果。

更新数据

使用 Mongoose 更新 MongoDB 数据库中的数据,需要基于定义好的数据模型和查询条件来操作。以下是将指定 User 文档的邮箱地址更新为新值的示例:

const User = require('./userModel');

const filter = { _id: '60b43f72b359ff1372b2fb0b' };
const update = { email: 'new-email@example.com' };

User.findOneAndUpdate(filter, update, { new: true }, (error, user) => {
  if (error) {
    console.log(error);
    return;
  }
  console.log(user);
});

在上面的示例中,使用 findOneAndUpdate() 方法查询符合指定条件的第一个文档,并将更新内容作为参数传递给方法。如果查询发生错误,则回调函数会打印错误;否则,打印更新后的文档内容。

删除数据

使用 Mongoose 删除 MongoDB 数据库中的数据,需要基于定义好的数据模型和查询条件来操作。以下是删除指定 User 文档的示例:

const User = require('./userModel');

const filter = { _id: '60b43f72b359ff1372b2fb0b' };

User.findOneAndRemove(filter, (error, user) => {
  if (error) {
    console.log(error);
    return;
  }
  console.log(user);
});

在上面的示例中,使用 findOneAndRemove() 方法查询符合指定条件的第一个文档,并将其删除。如果查询发生错误,则回调函数会打印错误;否则,打印被删除的文档内容。

结论

使用 Mongoose,可以方便地在 Node.js 应用程序中与 MongoDB 数据库进行交互,而无需编写低级的数据库管理代码。定义模型、查询、更新和删除数据都是简单而直观的。