繁体   English   中英

findOneAndUpdate猫鼬查询返回旧数据库值

[英]findOneAndUpdate mongoose query returning old database value

以下是我的代码快照,我遇到了使用{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});
});

});

我通过添加.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});
    })

});

帮助链接-> 猫鼬-exec函数有什么作用?

您需要添加选项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);
      }
  });
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM