When uploading a single image i.e., uploadResults only has one object -the following works fine.
When uploading multiple images it doesn't. The image object gets created correctly in the db but the album object has repeat images. For example, if I upload image1 and image2, album.Images should simply be [image1, image2] but instead it will be [image1, image2, image2]. I believe the issue is the timing of the callbacks within the foreach but can't quite pinpoint the issue..
uploadResults.forEach(function(uploadedItem) {
var image = new Images({
imageUrl: uploadedItem.url,
});
image.save(function (err, doc) {
album.Images.push(doc.id);
album.save(function(err, doc) {
//err handling...
});
});
});
Why are you saving the album on each iteration? Use Promise (probably need a polyfill for all). Use es6-promise:
const Promise = require('es6-promise').Promise;
let promises = [];
uploadResults.forEach(uploadedItem => {
let promise = new Promise((resolve, reject) => {
let image = new Images({
imageUrl: uploadedItem.url,
});
image.save((err, doc) => {
album.Images.push(doc.id);
// No saving here
});
});
promises.push(promise);
});
Promise
.all(promises)
.then(() => {
album.save((error, doc) => {
// rest of code
});
});
I've gotten it to work by only running album.save() on the final iteration.
uploadResults.forEach(function(uploadedItem, idx, array) {
var image = new Images({
imageUrl: uploadedItem.url,
});
image.save(function (err, doc) {
album.Images.push(doc.id);
if (idx === array.length - 1) {
album.save(function(err, doc) {
//err handling...
});
}
});
});