以下是我的代码快照,我遇到了使用{new:true}作为附加参数的解决方案,但我无法将其与.then()函数一起使用。我需要一些方法来检索更新的值。
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});
});
});
答案 0 :(得分:2)
我通过添加.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});
})
});
帮助链接 - > Mongoose - What does the exec function do?
答案 1 :(得分:0)
您需要添加选项new: true
才能获取更新的文档。
http://mongoosejs.com/docs/api.html#model_Model.findOneAndUpdate
如果没有回调函数,就无法使用此选项。
代码示例:
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);
}
});
});