简体   繁体   中英

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. 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.

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?

You need to add the options new: true in order to get the updated document. 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);
      }
  });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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