简体   繁体   中英

How to do a findOneAndUpdate with bluebird promises (mongoose)

I cannot find any examples on how to resolve promises with bluebird when using mongoose's findOneAndUpdate.

var Promise = require("bluebird");
var mongoose = Promise.promisifyAll(require('mongoose'));

//actions is an array of objects with queries and upsert data

var promises = actions.map(function(arr) {
    return MyModel.findOneAndUpdate(arr.query, arr.upsertData, {'upsert': true}, function (err, doc) {
        if (err) {
            console.log('Error: ', err);
            //return err;
        } else {
            console.log('doc: ', doc);
            //return Promise.resolve();
        }
    });
});
//once all db transactions are finished:
Promise.all(promises)
    .then(function() {

        console.log('all done');

        //this is where I want to output all the documents once they are updated or added

    })
    .error(function(err) {
        console.log('error:', err);
    });

So far, I've looked at bluebird and also async. I need to pass different options to the query, which I could not get to work with either library.

Mongoose's Query class, an instance of which findOneAndUpdate() returns, has an .exec() method that returns a promise:

var promises = actions.map(function(arr) {
  return MyModel.findOneAndUpdate(arr.query, arr.upsertData, {'upsert': true}).exec();
});

You get the results in an array:

Promise.all(promises).then(function(results) { ... });

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