thousight thousight - 5 months ago 21
Node.js Question

Mongoose update array function not working

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!

Answer

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