首页 > 解决方案 > 取消 Promise.all 一次拒绝时更新 MongoDB

问题描述

我有两个模型:用户和项目。

User: name, projects [ { id, role } ]
Project: name, members []

我编写了一个函数来将成员(来自用户)添加到项目。我的代码:

const addMember = async (req, res, next) => {
    const { userId, role, projectId } = req.body
    Promise.all([
        Project.findByIdAndUpdate(projectId, { $push: {members: userId}}),
        User.findByIdAndUpdate(userId, { $push: {projects: { id: userId, role: role}} })
    ]).then(values => {
        if (!values[0] || !values[1]) return next("Can not find")
        return res.json({
            result: 'ok',
            message: "Add member successfully!",
        })
    }).catch(error => next(error))
}

但它不像我预期的那样工作。如果 projectId 错误,Promise 中的嵌套方法 1 不工作但嵌套方法 2 仍然工作,数据库将被更新。和userId一样错。

一旦出错,如何返回错误?

标签: javascriptmongoose

解决方案


而不是findByIdAndUpdatePromise.all块中调用函数。您可以将代码分成两部分。

1)定义findById仅检查记录是否存在的update函数和更新条目的函数

2)分别执行findByIdupdate代码Promise.all

const addMember = async (req, res, next) => {
    const { userId, role, projectId } = req.body

    Promise.all([
      Project.findById(projectId, { $push: {members: userId}}),
      User.findById(userId, { $push: {projects: { id: userId, role: role}} })
    ]).then(values => {
        if (!values[0] || !values[1]) return next("Can not find")

        Promise.all([
          Project.update(projectId, { $push: {members: userId}}),
          User.update(userId, { $push: {projects: { id: userId, role: role}} })
        ]).then(values => {
          return res.json({
            result: 'ok',
            message: "Add member successfully!",
          })
        })
    }).catch(error => next(error))
}

推荐阅读