8

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.

hong4rc
  • 3,999
  • 4
  • 21
  • 40
Connor Black
  • 6,921
  • 12
  • 39
  • 70

2 Answers2

3

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.

skieter
  • 449
  • 4
  • 6
-1

In the line you're putting

for account in user['accounts']

you're creating a new variable, independent of the User model instance. You could use that variable to show the data (for example through a REST API) but not for modify the User model instance. aka. You are modifying another variable.

Instead, try to modify the user you're getting from the findOne() query and save it.

Orlando
  • 1,509
  • 2
  • 19
  • 27