From c5200e26498ffcd2b560e3a3cf8ba2795bbf603f Mon Sep 17 00:00:00 2001 From: Hage Yaapa Date: Thu, 11 Jul 2019 15:33:34 +0530 Subject: [PATCH] fix: preserve id on update Don't delete the id on update --- lib/mongodb.js | 11 ++++++----- test/mongodb.test.js | 21 +++++++++++++++++++++ 2 files changed, 27 insertions(+), 5 deletions(-) diff --git a/lib/mongodb.js b/lib/mongodb.js index a63928c76..18567c857 100644 --- a/lib/mongodb.js +++ b/lib/mongodb.js @@ -1608,23 +1608,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; diff --git a/test/mongodb.test.js b/test/mongodb.test.js index 343ea9660..611b321f3 100644 --- a/test/mongodb.test.js +++ b/test/mongodb.test.js @@ -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,