SwimmingG
SwimmingG

Reputation: 662

Mongoose findOneAndUpdate returns parameters in different order

I'm currently working with mongoose and I've come across something which I find very strange.

My code is as follows:

      Challenge.findOneAndUpdate({ _id: req.params.challengeId, users: req.user._id }, { $push: { submissions: submission._id } }, { new: true })
      .then(function(err, challengeUpdated) {
        console.log(challengeUpdated);
        console.log(err);
        if (err) {
          console.log('The error is : ');
          console.log(err);
          return res.status(401).json({ message: 'Error saving submission' });
        }
         else {
          return res.json(submission);
        }
      })

Note how I have function(err, challengeUpdated), in the docs here: http://mongoosejs.com/docs/api.html#model_Model.findOneAndUpdate, it says it should be this way round, but when I log them I err prints the object, and challengeUpdated prints either undefined / null. Changing the parameters around seems like I hack, so I was wondering whether there was something obvious that I'm doing wrong here.

Note: It is possible for the req.user._id not to be in users. Which is the error that I'm trying to find.

Looking at the answers to this question: Mongoose: findOneAndUpdate doesn't return updated document, it seems like the answers have it the same way round as me.

Hoping someone else faced this issue?

Note: I'm using mongoose v5.5.1.

Upvotes: 0

Views: 590

Answers (1)

nicholaswmin
nicholaswmin

Reputation: 22979

Your problem is that you are using error-first callback arguments in Promise-based code.

This is how it should be when using Promise interface:

Challenge.findOneAndUpdate({ _id: req.params.challengeId, users: req.user._id }, { $push: { submissions: submission._id } }, { new: true })
  .then((challengeUpdated) => {
    console.log('Success!')
    console.log(challengeUpdated)
  })
  .catch((err) => {
    console.error('An error occured', err)
  })

function(err, result) { } is a pattern reserved for callback-style code, not for Promises.

Upvotes: 2

Related Questions