简体   繁体   中英

Mongoose save creates duplicates inside async.each

I processed an array with async to save and validate data. This is what i'm processing:

var guests = [{
  "email": "first@email.com",
  "name": "First guest"
},{
  "email": "second@email.com",
  "name": "Second guest"
}];

I'm looping through this array and saving results one by one, but if i have more than one guest, it will create duplicates in my mongoose document. How can i prevent that? Here is the code that processes the guests:

Posts.findOne({ '_id': req.params.id }, function (err, post) {

  async.each(guests, function(guest, callback) {

      post.guests.push({
        "email": guest.email,
        "name": guest.name
      });

      post.save(function (err) {
        //process error, send email etc...
        callback();
      });

    },
    function(err){
      //return response
    }
  );

}

As async.each runs in parallel, multiple documents would pass duplication check. A bit slower but async.eachSeries should solve the problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM