Home Sequelize Transaction inside forEach loop
Reply: 0

Sequelize Transaction inside forEach loop

user2030
1#
user2030 Published in April 26, 2018, 1:43 pm

I'm trying to use transaction inside forEach loop using async/await syntax of Node 7.0+

When I try to print committed transaction response in console, I'm able to see the values but those same values are not committed in to DB.

Below is the code :

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++
    }

})
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.560482 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO