Reputation: 23
I found an interesting problem on loopback. I was confused when I was adding records with findOrCreate
. Let's see the example:
for (var x = 0; x < 10; x++) {
console.log(x);
var Log = app.models.Log;
Log.findOrCreate({
where: {
modelName: '123'
}
}, {
modelName: '123'
}, function(err, log) {
if (err) return;
if (log) {
console.log("+ " + log.id);
}
});
}
I think it should create 1 record with modelName
'123' only, but I got 10 finally.
Is there something wrong?
Upvotes: 1
Views: 4636
Reputation: 1888
That's expected. You are running the code synchronously. If you run it in an asynchronous way, you will see only one document being created. Try this:
var arr = new Array(10);
async.eachSeries(arr, function (pos, callback) {
console.log(pos);
Log.findOrCreate({
where: {
txt: '123'
}
}, {
txt: '123'
}, function (err, log) {
if (err) return;
console.log("+ " + log.id);
callback();
});
}, function (err) {
if (err) {
throw err;
}
}
);
Upvotes: 1