From e60fc5b0c32e1ff383611666a07d617c6eed6ee5 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 | 10 ++++++++++ 2 files changed, 16 insertions(+), 5 deletions(-) diff --git a/lib/mongodb.js b/lib/mongodb.js index 12b396f2b..9b270b725 100644 --- a/lib/mongodb.js +++ b/lib/mongodb.js @@ -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; diff --git a/test/mongodb.test.js b/test/mongodb.test.js index c8877f933..67ae3779a 100644 --- a/test/mongodb.test.js +++ b/test/mongodb.test.js @@ -1032,6 +1032,16 @@ describe('mongodb connector', function() { }); describe('updateAll', function() { + it('should preserve the id', async function() { + let user = await User.create({name: 'Al', age: 31, email: 'al@strongloop'}); + const userId = user.id; + user = user.toObject(); + user.age = 100; + + await User.update(user); + user.should.have.property('id', userId); + }); + it('should update the instance matching criteria', function(done) { User.create({name: 'Al', age: 31, email: 'al@strongloop'}, function( err1,