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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With