node-orm2 icon indicating copy to clipboard operation
node-orm2 copied to clipboard

Insert many rows if they doesn't exists

Open mitchpolska opened this issue 13 years ago • 2 comments

My code inserts two times the same values from array (last one). Why ? How to insert many rows but only if they doesn't exists ?

    for x of species # two elements 36 and 37
        data = { movie_id : id, species_id : species[x].id }
        console.log data
        MovieSpecies.exists data, (err, exists) ->
            if exists == false
                MovieSpecies.create data, (err, items) ->
                    console.log items

mitchpolska avatar Jun 24 '13 20:06 mitchpolska

Aren't you tasting a bit of variable hoisting? Try this (sorry, I don't know CoffeeScript):

for (var x in species) {
    (function (data) {
        console.log(data);
        MovieSpecies.exists(data, function (err, exists) {
            if (!exists) {
                MovieSpecies.create(data, function (err, items) {
                    console.log(items);
                });
            }
        });
    })({ movie_id: id, species_id : species[x].id });
}

dresende avatar Jun 25 '13 12:06 dresende

If you find the origin of the problem is not hoisting, please reopen.

dresende avatar Jul 04 '13 08:07 dresende