Skip to content

Commit

Permalink
Merge pull request #14288 from Automattic/vkarpov15/gh-14281
Browse files Browse the repository at this point in the history
fix(model): throw readable error when calling `Model()` with a string instead of `model()`
  • Loading branch information
vkarpov15 authored Jan 24, 2024
2 parents 2a7fdef + a36a180 commit 0d54bea
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 1 deletion.
11 changes: 10 additions & 1 deletion lib/model.js
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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

0 comments on commit 0d54bea

Please sign in to comment.