0

I'm trying to update my values by first find the object, then push a value into the 2 arrays, and then update the original value. The object can be found and the values can be pushed into the arrays. However, the update function seems to be unable to detect the changes, therefore it couldn't update the values in the database:

{
    "ok": 1,
    "nModified": 0,
    "n": 0,
    "lastOp": "0",
    "electionId": "576dec4e2c52240b7a5bca5e"
}

Here is my function that tries to update the values:

Skills.findOne({ skillsCat: req.body.skillsCat }, (err, skills)=> {
  if (err) {
      res.send(err)
      return
  }
  if (skills) {
    skills.skillName.push(req.body.skillName)
    skills.percent.push(req.body.percent)
    skills.markModified('skillName')
    skills.markModified('percent')
    return skills
  }
})
.then(skills=> {
    Skills.update( { _id: req.body._id }, { $set: skills }, (err, updated)=> {
        if (err) {
            res.send(err)
            return
        }
        res.json({
            message: 'Skill info updated successfully',
            'database response': updated
        })
    })
})

I've tried putting the update function inside the second if statement, but it gets me the same result.

Does anyone know what's wrong and how can I fix this? Thanks!

1 Answer 1

1

The code is mixing the use of callbacks and promises. To use promises-only...

Skills.findOne({ skillsCat: req.body.skillsCat }).exec().then(skills => {
    if (skills) {
        // ...
        return Skills.update({ _id: req.body._id }, { $set: skills });
    } else {
        return null;   // or, if this is an error in your app, throw it
    }
})
.then(skills=> {
    if (!skills) { // handle not found here }
    else {
        res.json({
            message: 'Skill info updated successfully',
            'database response': updated
        });
    }
})
.catch(err => { // handle errors here })
Sign up to request clarification or add additional context in comments.

1 Comment

I actually figured something out later. Instead of returning Skills.update(...), I returned skills.save(). And it worked.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.