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(model): ignore falsy last argument to create() for backwards compatibility #13493

Merged
merged 1 commit into from
Jun 9, 2023
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
18 changes: 13 additions & 5 deletions lib/model.js
Original file line number Diff line number Diff line change
Expand Up @@ -2812,19 +2812,27 @@ Model.create = async function create(doc, options) {
} else {
const last = arguments[arguments.length - 1];
options = {};
if (typeof last === 'function' || (arguments.length > 1 && !last)) {
if (typeof options === 'function' ||
typeof arguments[2] === 'function') {
throw new MongooseError('Model.create() no longer accepts a callback');
}
const hasCallback = typeof last === 'function' ||
typeof options === 'function' ||
typeof arguments[2] === 'function';
if (hasCallback) {
throw new MongooseError('Model.create() no longer accepts a callback');
} else {
args = [...arguments];
// For backwards compatibility with 6.x, because of gh-5061 Mongoose 6.x and
// older would treat a falsy last arg as a callback. We don't want to throw
// an error here, because it would look strange if `Test.create({}, void 0)`
// threw a callback error. But we also don't want to create an unnecessary document.
if (args.length > 1 && !last) {
args.pop();
}
}

if (args.length === 2 &&
args[0] != null &&
args[1] != null &&
args[0].session == null &&
last &&
getConstructorName(last.session) === 'ClientSession' &&
!this.schema.path('session')) {
// Probably means the user is running into the common mistake of trying
Expand Down
8 changes: 8 additions & 0 deletions test/model.create.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,14 @@ describe('model', function() {
assert.ok(doc._id);
});
});

it('ignores undefined last arg (gh-13487)', async function() {
await B.deleteMany({});
await B.create({ title: 'foo' }, void 0);
const docs = await B.find();
assert.equal(docs.length, 1);
assert.equal(docs[0].title, 'foo');
});
});
});
});
Loading