在forEach循环内部进行Sequelize Transaction

时间:2018-04-16 13:00:46

标签: node.js postgresql sequelize.js

我尝试使用Node 7.0 +的forEach循环中使用事务

当我尝试在控制台中打印已提交的事务响应时,我能够看到这些值,但这些值没有提交到DB。

以下是代码:

documentInfo.forEach(async (doc) => { // array of documentInfo
    var frontImgName = await module.exports.uploadImage(docFiles, doc.front, req, res )
    var backImgName = await module.exports.uploadImage(docFiles, doc.back, req, res )

    var checkKycDoc = await KYCDocument.findOne({
        where: {
            kyc_id: checkUserKyc.dataValues.kyc_id,
            user_id: checkUserKyc.dataValues.user_id
        }
    })

    if (checkKycDoc) { //update
        var updateDocument = await KYCDocument.update({
            document_name: doc.document_name,
            front_image: frontImgName,
            back_image: backImgName
        }, {
            where: {
                kyc_id: checkUserKyc.dataValues.kyc_id,
                user_id: checkUserKyc.dataValues.user_id
            },
        }, {transaction})

        log('updateDocument', updateDocument.dataValues)

    } else { // insert
        var newKycDocument = await new KYCDocument({
            kyc_id: checkUserKyc.dataValues.kyc_id,
            user_id: checkUserKyc.dataValues.user_id,
            document_name: doc.document_name,
            front_image: frontImgName,
            back_image: backImgName,
            status: true
        }, {transaction})

        log('newKycDocument', newKycDocument.dataValues)
    }
    if (rowCount === documentInfo.length) {
        await transaction.commit() // transaction is printed on this line
        log('KYC has been uploaded successfully')
        helpers.createResponse(res, constants.SUCCESS,
            messages.KYC_UPLOAD_SUCCESS,
            {'error': messages.KYC_UPLOAD_SUCCESS}
        )
    } else {
        rowCount++
    }

})

1 个答案:

答案 0 :(得分:0)

问题出在create方法中。

要解决此问题,我必须使用以下方法创建新行:

var newKycDocument = await KYCDocument.create({
    kyc_id: checkUserKyc.dataValues.kyc_id,
    user_id: checkUserKyc.dataValues.user_id,
    document_name: doc.document_name,
    front_image: frontImgName,
    back_image: backImgName
}, {transaction})

我错过了.create方法。