@@ -65,6 +65,7 @@ const STATES = require('./connectionstate');
6565const util = require ( 'util' ) ;
6666const utils = require ( './utils' ) ;
6767const MongooseBulkWriteError = require ( './error/bulkWriteError' ) ;
68+ const minimize = require ( './helpers/minimize' ) ;
6869
6970const VERSION_WHERE = 1 ;
7071const VERSION_INC = 2 ;
@@ -341,7 +342,19 @@ Model.prototype.$__handleSave = function(options, callback) {
341342 }
342343
343344 _applyCustomWhere ( this , where ) ;
344- this [ modelCollectionSymbol ] . updateOne ( where , delta [ 1 ] , saveOptions ) . then (
345+
346+ const update = delta [ 1 ] ;
347+ if ( this . $__schema . options . minimize ) {
348+ minimize ( update ) ;
349+ // minimize might leave us with an empty object, which would
350+ // lead to MongoDB throwing a "Update document requires atomic operators" error
351+ if ( Object . keys ( update ) . length === 0 ) {
352+ handleEmptyUpdate . call ( this ) ;
353+ return ;
354+ }
355+ }
356+
357+ this [ modelCollectionSymbol ] . updateOne ( where , update , saveOptions ) . then (
345358 ret => {
346359 ret . $where = where ;
347360 callback ( null , ret ) ;
@@ -353,6 +366,17 @@ Model.prototype.$__handleSave = function(options, callback) {
353366 }
354367 ) ;
355368 } else {
369+ handleEmptyUpdate . call ( this ) ;
370+ return ;
371+ }
372+
373+ // store the modified paths before the document is reset
374+ this . $__ . modifiedPaths = this . modifiedPaths ( ) ;
375+ this . $__reset ( ) ;
376+
377+ _setIsNew ( this , false ) ;
378+
379+ function handleEmptyUpdate ( ) {
356380 const optionsWithCustomValues = Object . assign ( { } , options , saveOptions ) ;
357381 const where = this . $__where ( ) ;
358382 const optimisticConcurrency = this . $__schema . options . optimisticConcurrency ;
@@ -369,14 +393,7 @@ Model.prototype.$__handleSave = function(options, callback) {
369393 callback ( null , { $where : where , matchedCount } ) ;
370394 } )
371395 . catch ( callback ) ;
372- return ;
373396 }
374-
375- // store the modified paths before the document is reset
376- this . $__ . modifiedPaths = this . modifiedPaths ( ) ;
377- this . $__reset ( ) ;
378-
379- _setIsNew ( this , false ) ;
380397} ;
381398
382399/*!
0 commit comments