I want to save data to MongoDB. But, before saving, I need to verify if a document with a certain id
already exists. The document will not be saved if it exists.
And I try to use the count()
method for it.
But, I don't understand why the i
variable increased inside the count()
method callback function. The argument per_page = 1
.
function storeData (data, per_page) {
var i;
for(i = 0; i < per_page; i++) {
console.log("Before i = " + i);
CoubVideo.count({id: data.coubs[i].id}, function (err, count) {
console.log("After i = " + i);
if (count == 0) {
var video = new CoubVideo(data.coubs[i]);
video.save(function (err) {
if (err) throw err;
console.log("Saved successfully!");
});
} else {
console.log("Duplicate");
}
});
}
}
Script output:
Before i = 0;
After i = 1;
Saved successfully!