Skip to content

Commit

Permalink
fix: preserve id on update
Browse files Browse the repository at this point in the history
Don't delete the id on update
  • Loading branch information
Hage Yaapa committed Jul 25, 2019
1 parent a6d0124 commit 51743c0
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 5 deletions.
11 changes: 6 additions & 5 deletions lib/mongodb.js
Original file line number Diff line number Diff line change
Expand Up @@ -1607,23 +1607,24 @@ MongoDB.prototype.update = MongoDB.prototype.updateAll = function updateAll(

where = self.buildWhere(modelName, where, options);

delete data[idName];
data = self.toDatabase(modelName, data);
let updateData = Object.assign({}, data);
delete updateData[idName];
updateData = self.toDatabase(modelName, updateData);

// Check for other operators and sanitize the data obj
data = self.parseUpdateData(modelName, data, options);
updateData = self.parseUpdateData(modelName, updateData, options);

this.execute(
modelName,
'updateMany',
where,
data,
updateData,
{upsert: false},
function(err, info) {
if (err) return cb && cb(err);

if (self.debug)
debug('updateAll.callback', modelName, where, data, err, info);
debug('updateAll.callback', modelName, where, updateData, err, info);

const affectedCount = info.result ? info.result.n : undefined;

Expand Down
21 changes: 21 additions & 0 deletions test/mongodb.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -1032,6 +1032,27 @@ describe('mongodb connector', function() {
});

describe('updateAll', function() {
it('should not mutate the input data object', async function() {
const user = await User.create({name: 'Al', age: 31, email: 'al@strongloop'});
const userId = user.id;
const userData = user.toObject();
userData.age = 100;

await User.update(userData);
userData.should.have.property('id', userId);
});

it('should not mutate the input model instance', async function() {
const user = await User.create({name: 'Al', age: 31, email: 'al@strongloop'});
const userId = user.id;
user.age = 100;
user.name = 'Albert';

await User.update(user);
user.should.have.property('id', userId);
user.should.have.property('name', 'Albert');
});

it('should update the instance matching criteria', function(done) {
User.create({name: 'Al', age: 31, email: 'al@strongloop'}, function(
err1,
Expand Down

0 comments on commit 51743c0

Please sign in to comment.