Search code examples
mongoosebluebird

Mongoose: How to call Model#save on docs returned by resolved Promise.all()?


I have the following code which uses Mongoose and Bluebird as mongoose's promise provider. What I am trying to achieve is to call Model#save on each of the elements of the array of mongoose docs returned when Promise.all() resolves, as illustrated below. This code is not working, and my guess is that when I call doc.save(), I am not doing it on an object recognized as an instance of a Mongoose Model. How can I fix this?

promises = [
  User.findById(userId).exec(),
  Post.findById(postId).exec()
];

var promisedDocs = Promise.all(promises)  // Should resolve to [{ user: {} }, {post: {} }]
  .then(function(results) {
    results.map(function(result) {
      // Extract the first property of object in array element.
      var doc = result[Object.keys(result)[0]];
      doc.someArrayProp.push(someValue);
      doc.save();
   });
});

Solution

  • The promise returned by Promise.all will resolve to [user, post], so you can directly operate on the documents in your results.map callback:

    var promisedDocs = Promise.all(promises)  // Resolves to [user, post]
      .then(function(results) {
        results.map(function(doc) {
          doc.someArrayProp.push(someValue);
          doc.save();
       });
    });