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?