node-orm2
node-orm2 copied to clipboard
Insert many rows if they doesn't exists
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
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 });
}
If you find the origin of the problem is not hoisting, please reopen.