【问题标题】:Mongoose - Remove all documents found using a promiseMongoose - 删除使用承诺找到的所有文档
【发布时间】:2018-05-07 09:12:27
【问题描述】:

我正在尝试将 cmets 作为文档而不是模型批量删除,因为我想稍后使用 pre-hook 删除方法。

下面的命令查找多个满足查询的文档,并尝试将每个评论一一删除。全部删除后,如果在它应该捕获它的阶段有任何错误,则调用 next() 函数。

Comment.find({'moment': this._id})
    .then(((comments) => Promise.each(comments, (comment) => comment.remove()))
    .then(next())
    .catch(next()));

但是这给了我一个错误并且没有删除评论

"TypeError: (中间值).then 不是函数"

【问题讨论】:

  • 不确定是否相关,但是您应该在 find 上调用 exec 以获得完整的承诺:comment.find({ ... }).exec()mongoosejs.com/docs/promises.html
  • 我得到 Promise.each 不是一个函数?

标签: node.js mongodb mongoose


【解决方案1】:

试试这个

   .then(() => next())
    .catch(() => next()));

或者这个(带有错误处理)

   .then(() => next())
    .catch(next);

【讨论】:

    【解决方案2】:

    我决定使用原生承诺,我可以使用 Promise.all 来实现这一点

    Comment.find({'moment': this._id})
        .then((comments) => {
            Promise.all(comments.forEach((comment) => comment.remove()))
                .then(next());
        });
    

    【讨论】:

      猜你喜欢
      • 2019-01-02
      • 1970-01-01
      • 2019-06-05
      • 2020-09-16
      • 1970-01-01
      • 2015-03-24
      • 2017-09-28
      • 2014-05-01
      • 1970-01-01
      相关资源
      最近更新 更多