javascript - 取消 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一样错。
一旦出错,如何返回错误?
解决方案
而不是
findByIdAndUpdate
在Promise.all
块中调用函数。您可以将代码分成两部分。
1)定义findById
仅检查记录是否存在的update
函数和更新条目的函数
2)分别执行findById
和update
代码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))
}
推荐阅读
- sql - 为什么不执行此 Azure SQL 存储过程?
- google-apps-script - Google Apps 脚本 - 基于时间的触发器
- html - 使用引导程序 4 排列 DIV 而不使用额外的 DIV
- objective-c - 如何在从 Objective-C 迁移到 Swift 时正确地将使用 NSKeyedArchiver 保存的旧数据迁移到新格式
- google-app-engine - 如何在 Gradle 中为 appengineRun 使用 jvmFlags 中的 projectDir?
- jestjs - 如何用 jest 测试减速器
- python - 如何替换在python中随机选择和删除的列表中的元素?
- https - 如何保护到服务器的发布请求有效负载?
- azure - Azure Application Insights 在从一个订阅移动到另一个订阅时保留日志数据?
- asp.net-core - InvalidOperationException:尝试激活 Controller 时无法解析类型“*Models.LandingPageContext”的服务