Skip to content

Commit 0d54bea

Browse files
authored
Merge pull request #14288 from Automattic/vkarpov15/gh-14281
fix(model): throw readable error when calling `Model()` with a string instead of `model()`
2 parents 2a7fdef + a36a180 commit 0d54bea

File tree

2 files changed

+17
-1
lines changed

2 files changed

+17
-1
lines changed

lib/model.js

+10-1
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ const EventEmitter = require('events').EventEmitter;
1313
const Kareem = require('kareem');
1414
const MongooseBuffer = require('./types/buffer');
1515
const MongooseError = require('./error/index');
16+
const ObjectParameterError = require('./error/objectParameter');
1617
const OverwriteModelError = require('./error/overwriteModel');
1718
const Query = require('./query');
1819
const SaveOptions = require('./options/saveOptions');
@@ -118,10 +119,15 @@ const saveToObjectOptions = Object.assign({}, internalToObjectOptions, {
118119

119120
function Model(doc, fields, skipId) {
120121
if (fields instanceof Schema) {
121-
throw new TypeError('2nd argument to `Model` must be a POJO or string, ' +
122+
throw new TypeError('2nd argument to `Model` constructor must be a POJO or string, ' +
122123
'**not** a schema. Make sure you\'re calling `mongoose.model()`, not ' +
123124
'`mongoose.Model()`.');
124125
}
126+
if (typeof doc === 'string') {
127+
throw new TypeError('First argument to `Model` constructor must be an object, ' +
128+
'**not** a string. Make sure you\'re calling `mongoose.model()`, not ' +
129+
'`mongoose.Model()`.');
130+
}
125131
Document.call(this, doc, fields, skipId);
126132
}
127133

@@ -3099,6 +3105,9 @@ Model.$__insertMany = function(arr, options, callback) {
30993105
const toExecute = arr.map((doc, index) =>
31003106
callback => {
31013107
if (!(doc instanceof _this)) {
3108+
if (doc != null && typeof doc !== 'object') {
3109+
return callback(new ObjectParameterError(doc, 'arr.' + index, 'insertMany'));
3110+
}
31023111
try {
31033112
doc = new _this(doc);
31043113
} catch (err) {

test/model.test.js

+7
Original file line numberDiff line numberDiff line change
@@ -7295,6 +7295,13 @@ describe('Model', function() {
72957295
const isCapped = await TestModel.collection.isCapped();
72967296
assert.ok(isCapped);
72977297
});
7298+
7299+
it('throws helpful error when calling Model() with string instead of model() (gh-14281)', async function() {
7300+
assert.throws(
7301+
() => mongoose.Model('taco'),
7302+
/First argument to `Model` constructor must be an object/
7303+
);
7304+
});
72987305
});
72997306

73007307

0 commit comments

Comments
 (0)