gpt4 book ai didi

node.js - 如何使用mongoose原生的promise(mpromise)查找文档然后保存

转载 作者:太空宇宙 更新时间:2023-11-03 22:46:49 24 4
gpt4 key购买 nike

我正在尝试将回调 hell 重构为 Promise。如何将 Promise 与 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);
});
}
});
}

最佳答案

你可以这样做:

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

关于node.js - 如何使用mongoose原生的promise(mpromise)查找文档然后保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30330711/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com