question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

`nModified: 1` returned by `.update()` when $addToSet makes no modification

See original GitHub issue

current 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:open
  • Created 5 years ago
  • Comments:13 (1 by maintainers)

github_iconTop GitHub Comments

2reactions
RobinJayaswalcommented, Aug 15, 2018

@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.

2reactions
lineuscommented, Aug 15, 2018

@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

#!/usr/bin/env node
'use strict';

const assert = require('assert');
const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost:27017/test', { useMongoClient: true });
const conn = mongoose.connection;
const Schema = mongoose.Schema;

const schema = new Schema({
  foo: [String]
});

const Test = mongoose.model('test', schema);

const test = new Test({ foo: ['bar'] });

async function run() {
  await conn.dropDatabase();
  await test.save();
  let res = await Test.update({ _id: test._id }, { $addToSet: { foo: 'bar'} });
  assert.strictEqual(res.nModified, 0);
  console.info(`Test passed on ${mongoose.version}`);
  return conn.close();
}

run();

Output:

issues: ./6861.js
Test passed on 4.13.9
issues:
Read more comments on GitHub >

github_iconTop Results From Across the Web

Why update with $addToSet return always 1 - Stack Overflow
This is working, my references are not updated if the element is already in the array but numAffected is always 1.. Is this...
Read more >
$addToSet — MongoDB Manual
$addToSet only ensures that there are no duplicate items added to the set and ... If you use $addToSet on a field that...
Read more >
Update expressions - Amazon DynamoDB
An update expression specifies how UpdateItem will modify the attributes of an ... causes DynamoDB to return the item as it appears after...
Read more >
Update Multiple Fields in a MongoDB Document - Baeldung
We can update the documents in a collection using various methods like update, replace and save. In order to change a specific field...
Read more >
Mongoose v6.8.2: API docs
Mongoose.prototype.connect(). Parameters. uri «String» mongodb URI to connect to. [options] «Object» passed down ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found