事务不回滚与异步/ Promise.all

时间:2019-08-26 13:37:52

标签: javascript mongoose transactions

我有两种模式:公司和用户。我编写了一个函数addMemberToCompany来向公司添加新成员。

但是效果不佳。当我运行它并输入假值时,该程序将引发错误,但不是roolbak。新数据继续推送到数据库。我该如何解决?

const Company = require('../models/company.model')
const User = require('../models/user.model')
const mongoose = require('../database/database')

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

    const companyId = req.user.role === "admin" ?
        req.body.companyId : req.user.company

    const session = await mongoose.startSession()
    session.startTransaction()
    try {
        const [company, user] = await Promise.all([
            Company.findByIdAndUpdate(companyId, { $push: { members: userId } }),
            User.findByIdAndUpdate(userId, { $set: { "company.id": companyId, "company.role": "employee" } } )
        ])

        if (!company || !user)
            throw "Can not find user or company"
        if (user.company.id || (company.members.indexOf(userId) > -1))
            throw "User already in company"

        await session.commitTransaction();
        session.endSession();

        return res.json({
            message: `Add member with id: ${userId} successfully!`,
        })
    } catch (error) {
        await session.abortTransaction();
        session.endSession();
        next(error)
    }
}

0 个答案:

没有答案