node.js - 我需要 MongoDB 在执行其他操作之前等待预删除 Hook

标签 node.js mongodb mongoose

我对使用 MongoDB(或任何其他数据库)相当陌生,并且我的费用管理器 Web 应用程序中有一个错误。

我有一些用户可以删除的集合(不是 MongoDB 集合,这只是我在网站上对它们的称呼)。从数据库中删除集合(以及对该集合的所有引用)后,我将获取所有其他集合。

问题在于,在应该删除的集合被删除之前,服务器已经在获取集合了。

这是当我尝试删除集合时在我的终端中显示的内容:

Mongoose: collections.findOne({ _id: ObjectId("5b3f5dc890a1702e96a8f59a") }, { fields: {} })
Mongoose: collections.findOne({ _id: ObjectId("5b3f5dc890a1702e96a8f59a") }, { fields: {} })
Mongoose: users.findOne({ _id: ObjectId("5b321af4b654523b93164187") }, { fields: {} })
Mongoose: collections.find({ user: ObjectId("5b321af4b654523b93164187") }, { fields: {} })
Mongoose: expenses.remove({ _collection: ObjectId("5b3f5dc890a1702e96a8f59a") }, {})
Mongoose: users.updateOne({ _id: ObjectId("5b321af4b654523b93164187") }, { '$pullAll': { collections: [ ObjectId("5b3f5dc890a1702e96a8f59a") ] }, '$inc': { __v: 1 } })
Mongoose: collections.remove({ _id: ObjectId("5b3f5dc890a1702e96a8f59a") }, {})

我试图研究如何等待钩子(Hook)完成,但找不到任何东西。我什至不知道这对我来说是否正确,所以我想我应该在这里问。

这是我的钩子(Hook):

collectionSchema.pre('remove', async function(next) {
  try {
    let user = await User.findById(this.user);
    user.collections.remove(this.id);

    this.model('Expense').remove({ _collection: this.id }, next);

    await user.save();

    return next();
  } catch(err) {
    return next(err);
  }
});

最佳答案

remove(...) promise 未正确链接到 async 函数内。另一个问题是 async 函数返回一个 Promise,而 next 与 Promise 是多余的,至少在 Mongoose 5 中是这样。

应该是这样的:

collectionSchema.pre('remove', async function() {
    let user = await User.findById(this.user);
    await user.collections.remove(this.id);    
    await this.model('Expense').remove({ _collection: this.id });
    await user.save();
});

关于node.js - 我需要 MongoDB 在执行其他操作之前等待预删除 Hook ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51211447/

相关文章:

node.js - Sequelize 的使用方法belongsTo

javascript - 如何删除 firebase 中的整个 Node ?

database - 使用 mongodb compass GUI 连接到 docker 中的 Mongodb

java - MongoDB 类似于 Java 中的操作

node.js - 如何在 Mocha 单元测试中使用 Mongoose ?

node.js - 使用NodeJS删除数据库中的多个用户

javascript - sails.js 一对多关系——变量所有者集合属性

javascript - 使用 $set 中的变量使用 node.js 更新 mongodb

mongodb - 使用 mgo Golang 从 MongoDB 子文档数组中解码

node.js - 为什么 Mongo 至少打开 5 个连接?