How to use the server-side shutdown event when all files are downloaded to jQuery File Upload

advertisements

I am using jQuery File Upload on express.js with jquery-file-upload-middleware and mongoose with mongoDB.

I want to upload images of a galery. The Galery object contains an array of Image objects, such as

var GalerySchema = new mongoose.Schema({
    images: [ImageSchema]
})

After each file has been uploaded asynchronously, I want to push it into the images array of my Galery object.

I tried to do the following server side:

// Is called everytime an image is uploaded
upload.on('end', function(fileInfo, rew, res){
    // Get the galery
    db.Galery.findOne({_id: req.fields.galery_id}, function(err, galery){

        // Create new Image object instance
        var image = new db.Image({src: fileInfo.name});

        // Save, in order to create auto generated _id
        image.save(function(err){
            if(err) {console.log(err); return; }

            // Add to Images array of Galery object
            galery.images.push(image);

            // Save galery with added image
            galery.save(function(err){
                if(err) { console.log(err); return; }
            });
        })
    });
});

Doing that, I get a well known [VersionError: No matching document found.], that, to my current knowledge, is due to the simultaneous access of the same mongodb document, since the upload happens asynchronously.

So in order to deal with the asynchronous fashion of the problem, it would be great to wait for all the uploads to finish, and then to insert the images one by one into the mongodb i.e. using async.parallel().

But how do I access the event of all uploads having been finished?

I know that browser side i can use the stop event. But first this does not contain any data about the uploaded files. Also, I want to do it the server-side.

Is there something like

upload.on('doneAll', function(allFilesInfo, req, res){...})?


You could use promises (Bluebird: https://github.com/petkaantonov/bluebird, npm install bluebird --save) and have something like this:

var BPromise = require('bluebird');

var uploadDone = new BPromise(function (resolve, reject) {

    // your image upload

});

uploadDone.then(function (result) {

   // upload complete here

}, function (error) {
   console.log("Error: ", error);
});