Tuesday 11 April 2017

sequalizejs - insert multiple records with order

I am using nodejs and back-end DB as PostgreSQL and the ORM is SequalizeJS. I want to add list of records into a table. The records are array of objects. I am iterating this array and pushing each record into database . But sometimes , the order is not maintained. Can you suggest some other way to fix this? . I want to add record one by one serially.

var users = <array of users>;
var createdUsers = [];
 for (var Index = 0; Index < users.length; Index++) {
        logger.debug("Insert User" + users[Index].user_name);
        models.User.create(users[Index]).then(function (user) {
            logger.debug("Inserted User" + user.user_name);
            createdUsers.push(user);
            if (createdUsers.length === users.length) {
                response.status(200).json(createdUsers);
            }
        }).catch(function (error) {
            response.status(500).json(error);            
        });
    }

users contains [{user_name:"AAA"},{user_name:"BBB"},{user_name:"CCC"},{user_name:"DDD"},{user_name:"EEE"},{user_name:"FFF"}].

After insert , sometimes the order will be BBB,AAA,FFF,EEE,DDD.



via JavaUser

No comments:

Post a Comment