I am trying to loop through an array and add the items in the array to a mongodb database if it doesnt exist already. Inside the loop I try to query my database if the next element in the array is already in the database. However inside the callback function, console.log always returns the last element of the array.
for(var j = 0 ; j < req.body.array.length; j++ ){
var currenttag = req.body.array[j];
Tag.findOne({tagname : currenttag},
function(err,tag){
if(tag){
console.log("tag exists");
}
else{
console.log(currenttag);//returns the last tag in the array for array.length times
var newtag = new Tag({tagname : currenttag});
newtag.save();
}
});
}