Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose save() method not writing to database

So I'm updating an attribute of a user sub document in mongoose, but it's not saving to my database.

Here's my function:

@User.findOne({'email': email}, (err, user) ->
    if err?
        callback(err)
    else if user?
        for account in user['accounts']
            if account['account_uuid'] is account_uuid

                account.state = "Verified"

                user.save((err, updated_user, numberTouched) ->
                    if err?
                        console.log err
                        return callback(err)
                    else
                        console.log 'Successfully verified account'
                        console.log updated_user

                        return callback(null, 'Successfully verified account')
                )
                return                        
        callback(new Error('No account for account_uuid'))
)

The really frustrating thing is that updated_user returns with the account.state attribute being "Verified" and the numberTouched variable returns as 1, meaning 1 document has been affected by the save. But when I check the user document in my DB, it's still the default value of "Pending".

Any thoughts?

P.S. I'm using a development database with MongoLab. But I don't think the problem is with them since I can update other attributes just fine.

like image 606
Connor Black Avatar asked Jan 26 '14 03:01

Connor Black


1 Answers

Assuming you are changing a mixed-type subdocument, you will need to call user.markModified('accounts') to let Mongoose know what's changed before you save.

However, if two of these operations happen concurrently, you could be losing data. I would recommend you use the findAndModify command, in conjunction with $elemMatch and $set operators.

like image 129
skieter Avatar answered Sep 30 '22 01:09

skieter