diff --git a/lib/model.js b/lib/model.js index 1ffca2b1b6e..0ced344223a 100644 --- a/lib/model.js +++ b/lib/model.js @@ -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'); @@ -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); } @@ -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) { diff --git a/test/model.test.js b/test/model.test.js index 314d77fc6f1..edff29ae047 100644 --- a/test/model.test.js +++ b/test/model.test.js @@ -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/ + ); + }); });