Tuesday 11 April 2017

Sequelize hooks, findall inside beforecreate working after record already inserted

When I try to run findall inside beforeCreate hook, the log files show that it inserted the record before performing the select.

I need to perform the select to modify the inserted data or reject the insert if no records is found.

here is a sample code

SalesPersonRoute.beforeCreate(function(SalesPersonRoute) {
    var models = require("../models/");
    var SalesPerson = models.SalesPerson;
    var Customer = models.Customer;
    var str = "" + SalesPersonRoute.SalesPersonId;
    var pad = "000";
    var ans = pad.substring(0, pad.length - str.length) + str;
    SalesPerson.findAll({
        where: {
            Code: ans
        }
    }).then(function(result) {
        if(result.length == 0){
            throw new Error("This SalesPerson Code doesn't exist! " + ans + " _ " + SalesPersonRoute.SalesPersonId);
            return sequelize.Promise.reject("This SalesPerson Code doesn't exist!")
        }
        else {
            console.log(result[0].dataValues.id);
            SalesPersonRoute.SalesPersonId = result[0].dataValues.id;
        }
    });
});



via M.A

No comments:

Post a Comment