`nModified: 1` returned by `.update()` when $addToSet makes no modification
See original GitHub issuecurrent behavior
User with id 1 has foo: ['bar']
currently in db. I run:
User.update({_id: 1}, {$addToSet: {foo: 'bar'}}).exec().then(res => {
console.log(res)
}
And it outputs { n: 1, nModified: 1, ok: 1 }
. But the document was not actually modified since it did not add anything to foo
, as bar
was already in the array.
expected behavior
I want to be able to check whether foo
array already contained ‘bar’, as this determines whether I continue. In a more concrete example, if the user gets points for doing an action, and completed actions are stored in an array, I want to be able to check if the user had already taken the action so I can avoid giving them points. I am aware I could just fetch the user from the db and check, but then if a user hits the api with concurrent requests using a script, they could get points multiple times. The $addToSet method with a check for updated or not seems like a great atomic way to do this, but it always returns nModified: 1 so I am unable to currently.
Versions Mongoose 4.13.9, MongoDB 3.6.2
Issue Analytics
- State:
- Created 5 years ago
- Comments:13 (1 by maintainers)
@lineus i do in fact have timestamps on. I suppose I expected the timestamps to only update in a real update, but now that I think about it they are probably implemented in a pre hook.
@RobinJayaswal do you have timestamps turned on by chance? or something else that might be updating a path in the document besides what your example shows? I tried to replicate what you’re seeing with the following code, but it doesn’t show the same behavior:
6861.js
Output: