返回

Mongoose 从入门到精通:从增删改查到联合查询

前端

简介

Mongoose 是一个流行的 Node.js 对象建模工具,用于与 MongoDB 数据库交互。它使您可以使用 JavaScript 编写代码来与 MongoDB 数据库交互,从而可以轻松地进行增删改查操作。

增删改查

const kitty = new Cat({ name: 'Zildjian' });

kitty.save(function (err, fluffy) {
  if (err) {
    console.error(err);
  } else {
    console.log('meow');
  }
});

Cat.findByIdAndRemove('5d378db94e70775c5434e642', function (err, cat) {
  if (err) {
    console.error(err);
  } else {
    console.log('cat removed');
  }
});

Cat.findByIdAndUpdate('5d378db94e70775c5434e642', { $set: { name: 'Fluffy' } }, function (err, cat) {
  if (err) {
    console.error(err);
  } else {
    console.log('cat updated');
  }
});

Cat.find({ name: 'Fluffy' }, function (err, cats) {
  if (err) {
    console.error(err);
  } else {
    console.log(cats);
  }
});

联合查询

Mongoose 还支持联合查询,这使您可以从多个集合中获取数据。例如,您可以使用以下代码从 cats 集合和 owners 集合中获取数据:

Cat.aggregate([
  { $lookup: {
    from: 'owners',
    localField: 'owner',
    foreignField: '_id',
    as: 'owner'
  }}
]).exec(function (err, cats) {
  if (err) {
    console.error(err);
  } else {
    console.log(cats);
  }
});

聚合

Mongoose 还支持聚合操作,这使您可以对数据进行分组、排序和计算。例如,您可以使用以下代码对 cats 集合中的数据进行分组并计算每个组的平均年龄:

Cat.aggregate([
  { $group: {
    _id: '$breed',
    avgAge: { $avg: '$age' }
  }}
]).exec(function (err, cats) {
  if (err) {
    console.error(err);
  } else {
    console.log(cats);
  }
});

总结

Mongoose 是一个功能强大的工具,可以帮助您轻松地与 MongoDB 数据库交互。它支持增删改查、联合查询和聚合操作,使您可以轻松地从数据库中获取和更新数据。