简体   繁体   中英

How to use javascript Promises for updating multiple docs in mongodb?

Hi I am writing a script that updates a mongodb database. My script does the following.

  1. Parses the file structure and prepares the schema object for all the files in the directory.
  2. It then queries the database and gets the file documents in the database.
  3. Then I use the array prepared in step 1 and step 2 to loop around to find an appropriate method ie save or update.
  4. disconnect the DB.

Due async nature of the mongodb API I had to use Promises. But I am anot able to acheive this through promises. Following is my code.

// a array that stores the file Json objects
var fileJsonArray = [];

//passing the filePath twice as one serves as the source for the icons and the other is the base location.
//Check the documentaion for the file for more details
directoryParser.parseDirectory(...);
//console.log(fileJsonArray);

//connect to db
var mongoose = mongoose || require('mongoose');
mongoose.Promise = require('bluebird');
var dbUrl = 'mongodb://'+ config.dbLocation + ':' + config.dbPort + '/' + config.dbName;
mongoose.connect(dbUrl);

// an array that contains all the promises
var promises = [];
//console.log(fileJsonArray);
//  get all the element
promises.push(File.find({}).exec()
    .catch(function(err){
        console.error('Error while getting all elements',err);
    })
    .then(function(err, allElements) {
        if(err) {
            console.error(err);
        } else {
            console.log(fileJsonArray);

            for (var i = 0; i < fileJsonArray.length; i++) {
                console.log(fileJsonArray[i].name);
                if(fileJsonArray[i] in allElements) {
                    var query = {name : fileJsonArray[i].name, tags: fileJsonArray[i].tags}
                        , update = {size : fileJsonArray[i].size, bmarkedasdeleted: true}
                        , options = {multi: false};
                    promises.push(File.update(query, update, options).exec());
                    allElements.splice(allElements.indexOf(fileJsonArray[i]),1);
                } else {
                    promises.push(fileJsonArray[i].save(function(err) {
                        if(err) {
                            console.error(fileJsonArray, err);
                        }
                    }));
                }
            }

            for (var i = 0; i < allElements.length; i++) {
                var query = {name : allElements[i].name, tags: allElements[i].tags}
                    , update = {bmarkedasdeleted: false}
                    , options = {multi: false};
                promises.push(File.update(query, update, options).exec());
            }
        }
    }));

    //console.log(promises);

    Promise.all(promises).then(function() {
        mongoose.disconnect();
        console.log('Disconnect Mongoose.');
    }).catch(function(err){
        console.log(err);
    });

Right now I am not able to save any value as the fileJsonArray is empty in the then for the find({}).exec().

Please advise. Also put in some comments if any clarification is required.

 File.find({}).exec() .then((allElements) => { var promises = []; for (var i = 0; i < fileJsonArray.length; i++) { if (fileJsonArray[i] in allElements) { var query = {name : fileJsonArray[i].name, tags: fileJsonArray[i].tags} , update = {size : fileJsonArray[i].size, bmarkedasdeleted: true} , options = {multi: false}; promises.push(File.update(query, update, options).exec()); allElements.splice(allElements.indexOf(fileJsonArray[i]), 1); } else { promises.push(fileJsonArray[i].save()); } } for (var i = 0; i < allElements.length; i++) { var query = {name : allElements[i].name, tags: allElements[i].tags} , update = {bmarkedasdeleted: false} , options = {multi: false}; promises.push(File.update(query, update, options).exec()); } return Promise.all(promises); }).then(() => { mongoose.disconnect(); console.log('Disconnect Mongoose.'); }).catch((err) => { console.log(err); }); 

Because Promise.all returns all the promises that have been resolved. You should execute File.find promise first and then collect other promises. Remember that you only can get other promises after File.find promise has been resolved.

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