[英]findOneAndUpdate mongoose query returning old database value
The following is my code snap, I've come across the solution of using {new: true} as an additional argument, but I'm not able to use it with .then() function. 以下是我的代码快照,我遇到了使用{new:true}作为附加参数的解决方案,但无法与.then()函数一起使用。 I need some way to retreive the updated value. 我需要某种方法来获取更新后的值。
router.post('/profile/:userId', checkAuth, (req, res, next) => {
Profile.findOneAndUpdate({
name: req.body.name,
age: req.body.age,
user: req.body.user,
education: req.body.education,
location: req.body.location,
phone: req.body.phone
}).then(result => {
console.log(result);
res.status(201).json(result);
}).catch(err => {
console.log(err);
res.status(500).json({error: err});
});
}); });
I solved it by adding .exec() to get a real promise as Mongoose queries do not return a promise. 我通过添加.exec()获得了真正的承诺来解决它,因为Mongoose查询不返回承诺。
router.post('/profile/:userId', checkAuth, (req, res, next) => {
var query = {};
var update = {
name: req.body.name,
age: req.body.age,
user: req.body.user,
education: req.body.education,
location: req.body.location,
phone: req.body.phone
};
var options = {upsert: true, new: true,};
Profile.findOneAndUpdate(query, update, options)
.exec()
.then( result => {
console.log(result);
res.status(201).json(result);
})
.catch( err => {
console.log(err);
res.status(500).json({error: err});
})
}); });
Help Link -> Mongoose - What does the exec function do? 帮助链接-> 猫鼬-exec函数有什么作用?
You need to add the options new: true
in order to get the updated document. 您需要添加选项new: true
才能获取更新的文档。 http://mongoosejs.com/docs/api.html#model_Model.findOneAndUpdate http://mongoosejs.com/docs/api.html#model_Model.findOneAndUpdate
There is no way ti use this options without a callback function. 如果没有回调函数,则无法使用此选项。
Code example: 代码示例:
router.post('/profile/:userId', checkAuth, (req, res, next) => {
Profile.findOneAndUpdate({
name: req.body.name,
age: req.body.age,
user: req.body.user,
education: req.body.education,
location: req.body.location,
phone: req.body.phone
},(err) => {
if (err) {
console.log(err);
res.status(500).json({error: err});
} else {
console.log(doc);
res.status(201).json(doc);
}
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.