我需要MongoDB等待删除前的钩子,然后再执行其他操作

时间:2018-07-06 13:26:01

标签: node.js mongodb mongoose

我刚开始使用MongoDB(或与此相关的任何其他数据库),但是我的费用管理器网络应用程序中存在一个错误。

我有一些用户可以删除的集合(不是 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") }, {})

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

这是我的钩子:

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);
  }
});

2 个答案:

答案 0 :(得分:2)

remove(...)的诺言在async函数中未正确链接。另一个问题是async函数返回一个promise,而next至少在Mongoose 5中对于promises是多余的。

应该是这样的:

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();
});

答案 1 :(得分:1)

事实证明,问题出在我用来删除集合的函数上。

显然我在使用一些我不理解的voo-doo魔术代码。 @estus的回答使我再次查看了我的代码,并研究了删除文档的正确方法:

await db.Collection.findByIdAndRemove(req.params.collection_id);

谢谢!

相关问题