如何使用mongoose native promise(mpromise)查找文档然后保存

时间:2015-05-19 16:05:51

标签: node.js express mongoose promise

我试图重构回调地狱以承诺。 如何将promises与findById.exec()一起使用,然后使用object.save()?

exports.changeAnimalName = function(req, res) {
 var Animal = mongoose.model('Animal', animalSchema);

 Animal.findById(id, function (err, animal) {
  if (animal) {
   animal.name=req.body.name;
   animal.save(function (err, animalSaved) {
    if (err) return console.error(err);
     return res.send(animalSaved);
    });
   }
 });
}

1 个答案:

答案 0 :(得分:5)

你可以这样做:

// No need to import the model every time
var Animal = mongoose.model('Animal', animalSchema);

exports.changeAnimalName = function(req, res) {
  // return the promise to caller
  return Animal.findById(id).exec().then(function found(animal) {
    if (animal) {
      animal.name = req.body.name;
      return animal.save(); // returns a promise
    }

    // you could throw a custom error here
    // throw new Error('Animal was not found for some reason');
  }).then(function saved(animal) {
    if (animal) {
      return res.send(animal);
    }

    // you could throw a custom error here as well
    // throw new Error('Animal was not returned after save for some reason');
  }).then(null, function(err) {
    // Could be error from find or save
    console.error(err);
    // respond with error
    res.send(err);

    // or if you want to propagate the error to the caller
    // throw err;
  });
}

或者你可以使用findByIdAndUpdate来简化它:

var Animal = mongoose.model('Animal', animalSchema);

exports.changeAnimalName = function(req, res) {
  // return the promise to caller
  return Animal.findByIdAndUpdate(id, {
    name: req.body.name
  }).exec().then(function updated(animal) {
    if (animal) {
      return res.send(animal);
    }

    // you could throw a custom error here as well
    // throw new Error('Animal was not returned after update for some reason');
  }).then(null, function(err) {
    console.error(err);
    // respond with error
    res.send(err);

    // or if you want to propagate the error to the caller
    // throw err;
  });
}