diff --git a/lib/document.js b/lib/document.js index 45da5eb3f1..aae953d587 100644 --- a/lib/document.js +++ b/lib/document.js @@ -677,6 +677,9 @@ Document.prototype.$init = function() { */ Document.prototype.$__init = function(doc, opts) { + if (doc == null) { + throw new ObjectParameterError(doc, 'doc', 'init'); + } this.$isNew = false; opts = opts || {}; diff --git a/test/model.test.js b/test/model.test.js index 109503249b..bad8fd7648 100644 --- a/test/model.test.js +++ b/test/model.test.js @@ -21,6 +21,7 @@ const ObjectId = Schema.Types.ObjectId; const DocumentObjectId = mongoose.Types.ObjectId; const EmbeddedDocument = mongoose.Types.Subdocument; const MongooseError = mongoose.Error; +const ObjectParameterError = require('../lib/error/objectParameter'); describe('Model', function() { let db; @@ -9164,6 +9165,31 @@ describe('Model', function() { assert.strictEqual(doc.name, 'Test2'); }); }); + describe('gh-15812', function() { + it('should throw ObjectParameterError when init is called with null', function() { + const doc = new mongoose.Document({}, new mongoose.Schema({ name: String })); + try { + doc.init(null); + assert.fail('Should have thrown an error'); + } catch (error) { + assert.ok(error instanceof ObjectParameterError); + assert.strictEqual(error.name, 'ObjectParameterError'); + assert.ok(error.message.includes('Parameter "doc" to init() must be an object')); + } + }); + + it('should throw ObjectParameterError when init is called with undefined', function() { + const doc = new mongoose.Document({}, new mongoose.Schema({ name: String })); + try { + doc.init(undefined); + assert.fail('Should have thrown an error'); + } catch (error) { + assert.ok(error instanceof ObjectParameterError); + assert.strictEqual(error.name, 'ObjectParameterError'); + assert.ok(error.message.includes('Parameter "doc" to init() must be an object')); + } + }); + }); });