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): throw readable error when calling Model() with a string instead of model() #14288

Merged
merged 1 commit into from Jan 24, 2024
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
11 changes: 10 additions & 1 deletion lib/model.js
Expand Up @@ -13,6 +13,7 @@ const EventEmitter = require('events').EventEmitter;
const Kareem = require('kareem');
const MongooseBuffer = require('./types/buffer');
const MongooseError = require('./error/index');
const ObjectParameterError = require('./error/objectParameter');
const OverwriteModelError = require('./error/overwriteModel');
const Query = require('./query');
const SaveOptions = require('./options/saveOptions');
Expand Down Expand Up @@ -118,10 +119,15 @@ const saveToObjectOptions = Object.assign({}, internalToObjectOptions, {

function Model(doc, fields, skipId) {
if (fields instanceof Schema) {
throw new TypeError('2nd argument to `Model` must be a POJO or string, ' +
throw new TypeError('2nd argument to `Model` constructor must be a POJO or string, ' +
'**not** a schema. Make sure you\'re calling `mongoose.model()`, not ' +
'`mongoose.Model()`.');
}
if (typeof doc === 'string') {
throw new TypeError('First argument to `Model` constructor must be an object, ' +
'**not** a string. Make sure you\'re calling `mongoose.model()`, not ' +
'`mongoose.Model()`.');
}
Document.call(this, doc, fields, skipId);
}

Expand Down Expand Up @@ -3099,6 +3105,9 @@ Model.$__insertMany = function(arr, options, callback) {
const toExecute = arr.map((doc, index) =>
callback => {
if (!(doc instanceof _this)) {
if (doc != null && typeof doc !== 'object') {
return callback(new ObjectParameterError(doc, 'arr.' + index, 'insertMany'));
}
try {
doc = new _this(doc);
} catch (err) {
Expand Down
7 changes: 7 additions & 0 deletions test/model.test.js
Expand Up @@ -7295,6 +7295,13 @@ describe('Model', function() {
const isCapped = await TestModel.collection.isCapped();
assert.ok(isCapped);
});

it('throws helpful error when calling Model() with string instead of model() (gh-14281)', async function() {
assert.throws(
() => mongoose.Model('taco'),
/First argument to `Model` constructor must be an object/
);
});
});


Expand Down