I have an array of names:
var names = ["Kelley", "Amy", "Mark"]
Assuming Person is just a Mongoose model for nodejs... I want to save each name as a document into mongodb with the following:
for(var i = 0; i < names.length; i++) {
name_now = names[i];
Person.findOne({ name: name_now},
function(err, doc) {
if(!err && !doc) {
var personDoc = new PersonDoc();
personDoc.name = name_now;
console.log(personDoc.name);
personDoc.save(function(err) {});
} else if(!err) {
console.log("Person is in the system");
} else {
console.log("ERROR: " + err);
}
}
)
}
I am having issues as I keep geting a "Error creating schedule: MongoError: E11000 duplicate key error index:..... dup key: {: "Mark"}". And it appears that it is trying to insert "Mark" (the last element in the list) 3 times as opposed to each of the names in the list.
When I try to print out the name of the current person in the loop (with the console.log(personDoc.name);), I get "Mark" 3 times... and it appears that it only saved "Mark" in the database and no one else... what is the proper way to deal with this?
During the findOne
callbacks, name_now
is always going to be set to the last name in names
because the for
loop completes before the first callback is even called. You need to create an immediate function to capture the current name_now
value during each iteration and preserve it for use in the callback:
for(var i = 0; i < names.length; i++) {
(function (name_now) {
Person.findOne({ name: name_now},
function(err, doc) {
if(!err && !doc) {
var personDoc = new PersonDoc();
personDoc.name = name_now;
console.log(personDoc.name);
personDoc.save(function(err) {});
} else if(!err) {
console.log("Person is in the system");
} else {
console.log("ERROR: " + err);
}
}
);
)(names[i]);
}