MongoDB
 SQL >> Datenbank >  >> NoSQL >> MongoDB

Beheben von doppelt erstellten Mongoose-Subdokumenten

Das Problem ist, dass deine forEach-Schleife nicht auf den asynchronen Callback von findById() wartet, bevor sie die nächste Iteration startet. Verwende eine der schleifenäquivalenten Methoden der async-Bibliothek – async.each, async.whilst oder async.until –, die auf jeden asynchronen Callback warten, bevor sie fortfahren, also im Grunde eine for-Schleife, die nachgibt.

var platform_docs = []; async.each(platforms, function(id, callback) { Platform.findById(id, function(err, platform) { if (platform) platform_docs.push(platform); callback(err); }); }, function(err) { // code to run on completion or err console.log(platform_docs); });

Für den gesamten Workflow lässt async.waterfall() jede Funktion ihre Ergebnisse an die nächste weitergeben. Die erste erstellt den Artikel, die zweite verwendet async.each(), um die Plattformen zu durchlaufen und jede mit findByIdAndUpdate() zu aktualisieren, und die letzte hängt diese Plattform-IDs an den neuen Artikel:

var newArticle = {}, platforms = req.body.platforms, date = req.body.date, split = date.split("/"); newArticle.title = req.body.title; newArticle.description = req.body.description; newArticle.date = split[2] + '/' + split[0] + '/' + split[2]; newArticle.link = req.body.link; newArticle.body = req.body.body; console.log(platforms); async.waterfall([ // Create the article function(callback) { var article = new Article(newArticle); article.save(function(err, article) { if (err) return callback(err); callback(null, article); }); }, // Query and update the platforms function(articleData, callback) { var platform_ids = []; async.each(platforms, function(id, callback) { Platform.findByIdAndUpdate( id, { "$push": { "articles": articleData._id } }, { "new": true }, function(err, platform) { if (platform) platform_ids.push(platform._id); callback(err); } ); }, function(err) { if (err) return callback(err); console.log(platform_ids); callback(null, { "article": articleData, "platform_ids": platform_ids }); }); }, // Update the article function(obj, callback) { var article = obj.article; obj.platform_ids.forEach(function(id) { article.platforms.push(id); }); article.save(function(err, article) { if (err) return callback(err); callback(null, article); }); } ], function(err, result) { /* This function gets called after the above tasks have called their "task callbacks" */ if (err) return next(err); console.log(result); res.redirect('articles/' + result._id); });

Da jetzt jeder asynchrone Schritt den Abschluss über seinen Callback signalisiert, wird der Artikel genau einmal erstellt, und keine Subdokumente werden durch sich überschneidende Iterationen dupliziert.