【问题标题】:How to use mongoose native promise (mpromise) to find a document and then save如何使用mongoose原生promise(mpromise)查找文档然后保存
【发布时间】:2015-07-31 13:57:14
【问题描述】:

我正在尝试重构回调地狱以承诺。 如何使用 findById.exec() 和 object.save() 的 Promise?

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);
    });
   }
 });
}

【问题讨论】:

  • 是的,这是真的,这只是查看完整示例的借口。

标签: node.js express mongoose promise


【解决方案1】:

你可以这样做:

// 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;
  });
}

【讨论】:

    猜你喜欢
    • 2015-07-24
    • 2017-06-18
    • 2015-07-02
    • 1970-01-01
    • 2021-05-15
    • 1970-01-01
    • 1970-01-01
    • 2014-04-07
    相关资源
    最近更新 更多