node.js - Avoid duplicates in mongoose insertMany() -
this question has answer here:
the question marked duplicate wrongly. different situation together.
i have database containing 27000 users. want insert more users csv file. each user can uniquely identified email id. want enter 43000 more such emails database. planning use
users.insertmany(emailarray,options,callback)
i want if email id exists, should not enter record database. checking each email id in database , updating individually seems inefficient. insertmany
seems faster. can work way around using insertmany
?
current approach::
csv() .fromfile(path) .on('json', (jsonobj) => { var email = jsonobj.email; delete jsonobj.email; var profile = jsonobj; user.addemails(email, profile, function (err, res) { if (err == "user exists") { console.log("user exists"); } else { console.log(res); } }) }) .on('done', (error) => { console.log('end'); fs.unlink(path); callback(null, "done"); })
add emails function
module.addemails = function(email, profile, callback){ user.findone({email: email}, function(err, res){ if(err) throw err; else if(res){ callback("user exists"); } else{ user.create({email: email, profile: profile},callback); } }) }
Comments
Post a Comment