Skip to content

Commit

Permalink
Merge pull request #11079 from gramliu/master
Browse files Browse the repository at this point in the history
Fix findByIdAndUpdate behavior with undefined id
  • Loading branch information
vkarpov15 committed Dec 24, 2021
2 parents 0c7023d + 7b60e4d commit 6d41296
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 0 deletions.
7 changes: 7 additions & 0 deletions lib/model.js
Original file line number Diff line number Diff line change
Expand Up @@ -2622,6 +2622,10 @@ function _decorateUpdateWithVersionKey(update, options, versionKey) {
* A.findByIdAndUpdate() // returns Query
*
* ####Note:
*
* If id is undefined and update is specified, an error will be thrown.
*
* ####Note:
*
* All top level update keys which are not `atomic` operation names are treated as set operations:
*
Expand Down Expand Up @@ -2677,6 +2681,9 @@ Model.findByIdAndUpdate = function(id, update, options, callback) {
throw new TypeError(msg);
}
return this.findOneAndUpdate({ _id: id }, undefined);
} else if (arguments.length > 1 && id === undefined) {
const msg = 'Model.findByIdAndUpdate(): id cannot be undefined if update is specified.';
throw new TypeError(msg);
}

// if a model is passed in instead of an id
Expand Down
8 changes: 8 additions & 0 deletions test/model.populate.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -316,6 +316,14 @@ describe('model: populate:', function() {
});
});

it('fail on undefined id update', function() {
const BlogPost = db.model('BlogPost', blogPostSchema);

assert.throws(function() {
BlogPost.findByIdAndUpdate(undefined, { $set: { _creator: {} } });
}, /id cannot be undefined/);
})

it('across DBs', function(done) {
const db = start();
const db2 = db.useDb('mongoose_test2');
Expand Down

0 comments on commit 6d41296

Please sign in to comment.