Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 891
reggie Avatar asked Dec 01 '25 23:12

reggie


1 Answers

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) { ... });
like image 113
robertklep Avatar answered Dec 04 '25 12:12

robertklep



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!