From a36a180b518cbc5c7fe846c68f8c0925ccc6eb68 Mon Sep 17 00:00:00 2001 From: Valeri Karpov Date: Wed, 24 Jan 2024 07:24:12 -0500 Subject: [PATCH] fix(model): throw readable error when calling `Model()` with a string instead of `model()` Fix #14281 --- lib/model.js | 11 ++++++++++- test/model.test.js | 7 +++++++ 2 files changed, 17 insertions(+), 1 deletion(-) 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/ + ); + }); });