0

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

});

Soham Das
  • 63
  • 2
  • 9

2 Answers2

2

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?

Soham Das
  • 63
  • 2
  • 9
0

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);
      }
  });
});
Hai Alaluf
  • 757
  • 7
  • 15
thejoin
  • 326
  • 2
  • 8