Skip to content

Commit

Permalink
fix(model): throw error when passing non-object to create()
Browse files Browse the repository at this point in the history
Fix #2037
  • Loading branch information
vkarpov15 committed Dec 4, 2017
1 parent d0d2d5f commit d90100e
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 1 deletion.
5 changes: 5 additions & 0 deletions lib/document.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ var MongooseError = require('./error');
var MixedSchema = require('./schema/mixed');
var Schema = require('./schema');
var ObjectExpectedError = require('./error/objectExpected');
var ObjectParameterError = require('./error/objectParameter');
var StrictModeError = require('./error/strict');
var ValidatorError = require('./schematype').ValidatorError;
var VirtualType = require('./virtualtype');
Expand Down Expand Up @@ -48,6 +49,10 @@ function Document(obj, fields, skipId, options) {
this.errors = undefined;
this.$__.$options = options || {};

if (obj != null && typeof obj !== 'object') {
throw new ObjectParameterError(obj, 'obj', 'Document');
}

var schema = this.schema;

if (typeof fields === 'boolean') {
Expand Down
10 changes: 9 additions & 1 deletion lib/model.js
Original file line number Diff line number Diff line change
Expand Up @@ -2043,7 +2043,7 @@ Model.create = function create(doc, callback) {
var Model = _this.discriminators && doc[discriminatorKey] ?
_this.discriminators[doc[discriminatorKey]] :
_this;
var toSave = doc instanceof Model ? doc : new Model(doc);
var toSave = doc;
var callbackWrapper = function(error, doc) {
if (error) {
if (!firstError) {
Expand All @@ -2054,6 +2054,14 @@ Model.create = function create(doc, callback) {
callback(null, { doc: doc });
};

if (!(toSave instanceof Model)) {
try {
toSave = new Model(toSave);
} catch (error) {
return callbackWrapper(error);
}
}

// Hack to avoid getting a promise because of
// $__registerHooksFromSchema
if (toSave.$__original_save) {
Expand Down

0 comments on commit d90100e

Please sign in to comment.