Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix findByIdAndUpdate behavior with undefined id #11079

Merged
merged 6 commits into from
Dec 24, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions lib/model.js
Original file line number Diff line number Diff line change
Expand Up @@ -2621,6 +2621,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 @@ -2676,6 +2680,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