0

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.

SwimmingG
  • 654
  • 2
  • 9
  • 29
  • it said `challenge` is not defined. did you define `challenge` anywhere? – Rupesh Mar 08 '18 at 11:58
  • @Rupesh This is Node.js mongoose code. – nicholaswmin Mar 08 '18 at 11:59
  • I know but you have to define your `chalange` .If you haveany schema . then you require that schema like `var Challenge= require('path of your schema');` – Rupesh Mar 08 '18 at 12:01
  • I have temporarily fixed it by switching the arguments around, but would like to double check whether that's Kosher. – SwimmingG Mar 08 '18 at 12:02
  • Yes, I require challenge at the top of the file, I didn't include since I didn't think it's directly relevant to the question. – SwimmingG Mar 08 '18 at 12:02
  • @SwimmingG because according to error you are not defining the `Challenge` properly , did you check the spelling? – Rupesh Mar 08 '18 at 12:05

1 Answers1

2

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.

nicholaswmin
  • 21,686
  • 15
  • 91
  • 167