This commit is contained in:
Jonasz Bigda
2023-03-25 21:51:42 +01:00
parent 0db1d5117e
commit b332e9ceb0
1044 changed files with 37502 additions and 63938 deletions

View File

@@ -62,7 +62,7 @@ function _createConstructor(schema, baseClass) {
const _embedded = function SingleNested(value, path, parent) {
const _this = this;
this.$parent = parent;
this.$__parent = parent;
Subdocument.apply(this, arguments);
this.$session(this.ownerDocument().$session());
@@ -147,7 +147,7 @@ SingleNestedPath.prototype.$conditionalHandlers.$exists = $exists;
* @api private
*/
SingleNestedPath.prototype.cast = function(val, doc, init, priorVal) {
SingleNestedPath.prototype.cast = function(val, doc, init, priorVal, options) {
if (val && val.$isSingleNested && val.parent === doc) {
return val;
}
@@ -169,16 +169,16 @@ SingleNestedPath.prototype.cast = function(val, doc, init, priorVal) {
}
return obj;
}, {});
options = Object.assign({}, options, { priorDoc: priorVal });
if (init) {
subdoc = new Constructor(void 0, selected, doc);
subdoc.init(val);
} else {
if (Object.keys(val).length === 0) {
return new Constructor({}, selected, doc);
return new Constructor({}, selected, doc, undefined, options);
}
return new Constructor(val, selected, doc, undefined, { priorDoc: priorVal });
return new Constructor(val, selected, doc, undefined, options);
}
return subdoc;
@@ -300,6 +300,26 @@ SingleNestedPath.prototype.discriminator = function(name, schema, value) {
return this.caster.discriminators[name];
};
/**
* Sets a default option for all SingleNestedPath instances.
*
* ####Example:
*
* // Make all numbers have option `min` equal to 0.
* mongoose.Schema.Embedded.set('required', true);
*
* @param {String} option - The option you'd like to set the value for
* @param {*} value - value for option
* @return {undefined}
* @function set
* @static
* @api public
*/
SingleNestedPath.defaultOptions = {};
SingleNestedPath.set = SchemaType.set;
/*!
* ignore
*/

View File

@@ -25,6 +25,7 @@ let MongooseArray;
let EmbeddedDoc;
const isNestedArraySymbol = Symbol('mongoose#isNestedArray');
const emptyOpts = Object.freeze({});
/**
* Array SchemaType constructor
@@ -60,6 +61,10 @@ function SchemaArray(key, cast, options, schemaOptions) {
}
}
if (options != null && options.ref != null && castOptions.ref == null) {
castOptions.ref = options.ref;
}
if (cast === Object) {
cast = Mixed;
}
@@ -81,16 +86,16 @@ function SchemaArray(key, cast, options, schemaOptions) {
if (typeof caster === 'function' &&
!caster.$isArraySubdocument &&
!caster.$isSchemaMap) {
this.caster = new caster(null, castOptions);
const path = this.caster instanceof EmbeddedDoc ? null : key;
this.caster = new caster(path, castOptions);
} else {
this.caster = caster;
if (!(this.caster instanceof EmbeddedDoc)) {
this.caster.path = key;
}
}
this.$embeddedSchemaType = this.caster;
if (!(this.caster instanceof EmbeddedDoc)) {
this.caster.path = key;
}
}
this.$isMongooseArray = true;
@@ -116,7 +121,7 @@ function SchemaArray(key, cast, options, schemaOptions) {
// Leave it up to `cast()` to convert the array
return arr;
};
defaultFn.$runBeforeSetters = true;
defaultFn.$runBeforeSetters = !fn;
this.default(defaultFn);
}
}
@@ -141,6 +146,10 @@ SchemaArray.schemaName = 'Array';
SchemaArray.options = { castNonArrays: true };
/*!
* ignore
*/
SchemaArray.defaultOptions = {};
/**
@@ -158,7 +167,6 @@ SchemaArray.defaultOptions = {};
* @param {*} value - value for option
* @return {undefined}
* @function set
* @static
* @api public
*/
SchemaArray.set = SchemaType.set;
@@ -191,7 +199,6 @@ SchemaArray._checkRequired = SchemaType.prototype.checkRequired;
* @param {Function} fn
* @return {Function}
* @function checkRequired
* @static
* @api public
*/
@@ -242,7 +249,13 @@ SchemaArray.prototype.enum = function() {
}
break;
}
arr.caster.enum.apply(arr.caster, arguments);
let enumArray = arguments;
if (!Array.isArray(arguments) && utils.isObject(arguments)) {
enumArray = utils.object.vals(enumArray);
}
arr.caster.enum.apply(arr.caster, enumArray);
return this;
};
@@ -255,23 +268,30 @@ SchemaArray.prototype.enum = function() {
*/
SchemaArray.prototype.applyGetters = function(value, scope) {
if (this.caster.options && this.caster.options.ref) {
if (scope != null && scope.$__ != null && scope.populated(this.path)) {
// means the object id was populated
return value;
}
return SchemaType.prototype.applyGetters.call(this, value, scope);
const ret = SchemaType.prototype.applyGetters.call(this, value, scope);
if (Array.isArray(ret)) {
const len = ret.length;
for (let i = 0; i < len; ++i) {
ret[i] = this.caster.applyGetters(ret[i], scope);
}
}
return ret;
};
SchemaArray.prototype._applySetters = function(value, scope, init, priorVal) {
if (this.casterConstructor instanceof SchemaArray &&
if (this.casterConstructor.$isMongooseArray &&
SchemaArray.options.castNonArrays &&
!this[isNestedArraySymbol]) {
// Check nesting levels and wrap in array if necessary
let depth = 0;
let arr = this;
while (arr != null &&
arr instanceof SchemaArray &&
arr.$isMongooseArray &&
!arr.$isMongooseDocumentArray) {
++depth;
arr = arr.casterConstructor;
@@ -280,7 +300,7 @@ SchemaArray.prototype._applySetters = function(value, scope, init, priorVal) {
// No need to wrap empty arrays
if (value != null && value.length > 0) {
const valueDepth = arrayDepth(value);
if (valueDepth.min === valueDepth.max && valueDepth.max < depth) {
if (valueDepth.min === valueDepth.max && valueDepth.max < depth && valueDepth.containsNonArrayItem) {
for (let i = valueDepth.max; i < depth; ++i) {
value = [value];
}
@@ -308,7 +328,8 @@ SchemaArray.prototype.cast = function(value, doc, init, prev, options) {
let l;
if (Array.isArray(value)) {
if (!value.length && doc) {
const len = value.length;
if (!len && doc) {
const indexes = doc.schema.indexedPaths();
const arrayPath = this.path;
@@ -333,39 +354,42 @@ SchemaArray.prototype.cast = function(value, doc, init, prev, options) {
}
}
if (!(value && value.isMongooseArray)) {
value = new MongooseArray(value, this.path, doc);
} else if (value && value.isMongooseArray) {
// We need to create a new array, otherwise change tracking will
// update the old doc (gh-4449)
value = new MongooseArray(value, this.path, doc);
}
options = options || emptyOpts;
const isPopulated = doc != null && doc.$__ != null && doc.populated(this.path);
if (isPopulated) {
value = MongooseArray(value, options.path || this._arrayPath || this.path, doc, this);
if (init && doc != null && doc.$__ != null && doc.populated(this.path)) {
return value;
}
if (this.caster && this.casterConstructor !== Mixed) {
const caster = this.caster;
const isMongooseArray = caster.$isMongooseArray;
const isArrayOfNumbers = caster.instance === 'Number';
if (caster && this.casterConstructor !== Mixed) {
try {
for (i = 0, l = value.length; i < l; i++) {
for (i = 0; i < len; i++) {
// Special case: number arrays disallow undefined.
// Re: gh-840
// See commit 1298fe92d2c790a90594bd08199e45a4a09162a6
if (this.caster.instance === 'Number' && value[i] === void 0) {
if (isArrayOfNumbers && value[i] === void 0) {
throw new MongooseError('Mongoose number arrays disallow storing undefined');
}
const opts = {};
if (options != null && options.arrayPath != null) {
opts.arrayPath = options.arrayPath + '.' + i;
} else if (this.caster._arrayPath != null) {
opts.arrayPath = this.caster._arrayPath.slice(0, -2) + '.' + i;
// Perf: creating `arrayPath` is expensive for large arrays.
// We only need `arrayPath` if this is a nested array, so
// skip if possible.
if (isMongooseArray) {
if (options.arrayPath != null) {
opts.arrayPathIndex = i;
} else if (caster._arrayParentPath != null) {
opts.arrayPathIndex = i;
}
}
value[i] = this.caster.cast(value[i], doc, init, void 0, opts);
value[i] = caster.applySetters(value[i], doc, init, void 0, opts);
}
} catch (e) {
// rethrow
throw new CastError('[' + e.kind + ']', util.inspect(value), this.path, e, this);
throw new CastError('[' + e.kind + ']', util.inspect(value), this.path + '.' + i, e, this);
}
}
@@ -384,12 +408,50 @@ SchemaArray.prototype.cast = function(value, doc, init, prev, options) {
throw new CastError('Array', util.inspect(value), this.path, null, this);
};
/*!
* ignore
*/
SchemaArray.prototype._castForPopulate = function _castForPopulate(value, doc) {
// lazy load
MongooseArray || (MongooseArray = require('../types').Array);
if (Array.isArray(value)) {
let i;
const len = value.length;
const caster = this.caster;
if (caster && this.casterConstructor !== Mixed) {
try {
for (i = 0; i < len; i++) {
const opts = {};
// Perf: creating `arrayPath` is expensive for large arrays.
// We only need `arrayPath` if this is a nested array, so
// skip if possible.
if (caster.$isMongooseArray && caster._arrayParentPath != null) {
opts.arrayPathIndex = i;
}
value[i] = caster.cast(value[i], doc, false, void 0, opts);
}
} catch (e) {
// rethrow
throw new CastError('[' + e.kind + ']', util.inspect(value), this.path + '.' + i, e, this);
}
}
return value;
}
throw new CastError('Array', util.inspect(value), this.path, null, this);
};
/*!
* Ignore
*/
SchemaArray.prototype.discriminator = function(name, schema) {
let arr = this; // eslint-disable-line consistent-this
let arr = this;
while (arr.$isMongooseArray && !arr.$isMongooseDocumentArray) {
arr = arr.casterConstructor;
if (arr == null || typeof arr === 'function') {
@@ -447,7 +509,7 @@ SchemaArray.prototype.castForQuery = function($conditional, value) {
Constructor.discriminators[val[Constructor.schema.options.discriminatorKey]]) {
Constructor = Constructor.discriminators[val[Constructor.schema.options.discriminatorKey]];
} else {
const constructorByValue = getDiscriminatorByValue(Constructor, val[Constructor.schema.options.discriminatorKey]);
const constructorByValue = getDiscriminatorByValue(Constructor.discriminators, val[Constructor.schema.options.discriminatorKey]);
if (constructorByValue) {
Constructor = constructorByValue;
}
@@ -537,18 +599,24 @@ handle.$all = cast$all;
handle.$options = String;
handle.$elemMatch = cast$elemMatch;
handle.$geoIntersects = geospatial.cast$geoIntersects;
handle.$or = handle.$and = function(val) {
if (!Array.isArray(val)) {
throw new TypeError('conditional $or/$and require array');
}
handle.$or = createLogicalQueryOperatorHandler('$or');
handle.$and = createLogicalQueryOperatorHandler('$and');
handle.$nor = createLogicalQueryOperatorHandler('$nor');
const ret = [];
for (const obj of val) {
ret.push(cast(this.casterConstructor.schema, obj));
}
function createLogicalQueryOperatorHandler(op) {
return function logicalQueryOperatorHandler(val) {
if (!Array.isArray(val)) {
throw new TypeError('conditional ' + op + ' requires an array');
}
return ret;
};
const ret = [];
for (const obj of val) {
ret.push(cast(this.casterConstructor.schema, obj));
}
return ret;
};
}
handle.$near =
handle.$nearSphere = geospatial.cast$near;

View File

@@ -94,18 +94,24 @@ SchemaBoolean.cast = function cast(caster) {
return this._cast;
}
if (caster === false) {
caster = v => {
if (v != null && typeof v !== 'boolean') {
throw new Error();
}
return v;
};
caster = this._defaultCaster;
}
this._cast = caster;
return this._cast;
};
/*!
* ignore
*/
SchemaBoolean._defaultCaster = v => {
if (v != null && typeof v !== 'boolean') {
throw new Error();
}
return v;
};
/*!
* ignore
*/
@@ -188,9 +194,15 @@ Object.defineProperty(SchemaBoolean, 'convertToFalse', {
*/
SchemaBoolean.prototype.cast = function(value) {
const castBoolean = typeof this.constructor.cast === 'function' ?
this.constructor.cast() :
SchemaBoolean.cast();
let castBoolean;
if (typeof this._castFunction === 'function') {
castBoolean = this._castFunction;
} else if (typeof this.constructor.cast === 'function') {
castBoolean = this.constructor.cast();
} else {
castBoolean = SchemaBoolean.cast();
}
try {
return castBoolean(value);
} catch (error) {
@@ -224,6 +236,33 @@ SchemaBoolean.prototype.castForQuery = function($conditional, val) {
return this._castForQuery($conditional);
};
/**
*
* @api private
*/
SchemaBoolean.prototype._castNullish = function _castNullish(v) {
if (typeof v === 'undefined' &&
this.$$context != null &&
this.$$context._mongooseOptions != null &&
this.$$context._mongooseOptions.omitUndefined) {
return v;
}
const castBoolean = typeof this.constructor.cast === 'function' ?
this.constructor.cast() :
SchemaBoolean.cast();
if (castBoolean == null) {
return v;
}
if (castBoolean.convertToFalse instanceof Set && castBoolean.convertToFalse.has(v)) {
return false;
}
if (castBoolean.convertToTrue instanceof Set && castBoolean.convertToTrue.has(v)) {
return true;
}
return v;
};
/*!
* Module exports.
*/

View File

@@ -10,11 +10,8 @@ const SchemaType = require('../schematype');
const handleBitwiseOperator = require('./operators/bitwise');
const utils = require('../utils');
const populateModelSymbol = require('../helpers/symbols').populateModelSymbol;
const Binary = MongooseBuffer.Binary;
const CastError = SchemaType.CastError;
let Document;
/**
* Buffer SchemaType constructor
@@ -124,36 +121,30 @@ SchemaBuffer.prototype.checkRequired = function(value, doc) {
SchemaBuffer.prototype.cast = function(value, doc, init) {
let ret;
if (SchemaType._isRef(this, value, doc, init)) {
// wait! we may need to cast this to a document
if (value === null || value === undefined) {
if (value && value.isMongooseBuffer) {
return value;
}
// lazy load
Document || (Document = require('./../document'));
if (value instanceof Document) {
value.$__.wasPopulated = true;
return value;
}
// setting a populated path
if (Buffer.isBuffer(value)) {
if (!value || !value.isMongooseBuffer) {
value = new MongooseBuffer(value, [this.path, doc]);
if (this.options.subtype != null) {
value._subtype = this.options.subtype;
}
}
return value;
} else if (!utils.isObject(value)) {
throw new CastError('Buffer', value, this.path, null, this);
}
// Handle the case where user directly sets a populated
// path to a plain object; cast to the Model used in
// the population query.
const path = doc.$__fullPath(this.path);
const owner = doc.ownerDocument ? doc.ownerDocument() : doc;
const pop = owner.populated(path, true);
ret = new pop.options[populateModelSymbol](value);
ret.$__.wasPopulated = true;
return ret;
if (value instanceof Binary) {
ret = new MongooseBuffer(value.value(true), [this.path, doc]);
if (typeof value.sub_type !== 'number') {
throw new CastError('Buffer', value, this.path, null, this);
}
ret._subtype = value.sub_type;
return ret;
}
return this._castRef(value, doc, init);
}
// documents
@@ -213,9 +204,9 @@ SchemaBuffer.prototype.cast = function(value, doc, init) {
*
* ####Example:
*
* var s = new Schema({ uuid: { type: Buffer, subtype: 4 });
* var M = db.model('M', s);
* var m = new M({ uuid: 'test string' });
* const s = new Schema({ uuid: { type: Buffer, subtype: 4 });
* const M = db.model('M', s);
* const m = new M({ uuid: 'test string' });
* m.uuid._subtype; // 4
*
* @param {Number} subtype the default subtype

View File

@@ -8,6 +8,7 @@ const MongooseError = require('../error/index');
const SchemaDateOptions = require('../options/SchemaDateOptions');
const SchemaType = require('../schematype');
const castDate = require('../cast/date');
const getConstructorName = require('../helpers/getConstructorName');
const utils = require('../utils');
const CastError = SchemaType.CastError;
@@ -97,18 +98,24 @@ SchemaDate.cast = function cast(caster) {
return this._cast;
}
if (caster === false) {
caster = v => {
if (v != null && !(v instanceof Date)) {
throw new Error();
}
return v;
};
caster = this._defaultCaster;
}
this._cast = caster;
return this._cast;
};
/*!
* ignore
*/
SchemaDate._defaultCaster = v => {
if (v != null && !(v instanceof Date)) {
throw new Error();
}
return v;
};
/**
* Declares a TTL index (rounded to the nearest second) for _Date_ types only.
*
@@ -131,7 +138,7 @@ SchemaDate.cast = function cast(caster) {
* new Schema({ createdAt: { type: Date, expires: '1.5h' }});
*
* // expire in 7 days
* var schema = new Schema({ createdAt: Date });
* const schema = new Schema({ createdAt: Date });
* schema.path('createdAt').expires('7d');
*
* @param {Number|String} when
@@ -141,7 +148,7 @@ SchemaDate.cast = function cast(caster) {
*/
SchemaDate.prototype.expires = function(when) {
if (!this._index || this._index.constructor.name !== 'Object') {
if (getConstructorName(this._index) !== 'Object') {
this._index = {};
}
@@ -205,9 +212,9 @@ SchemaDate.prototype.checkRequired = function(value, doc) {
*
* ####Example:
*
* var s = new Schema({ d: { type: Date, min: Date('1970-01-01') })
* var M = db.model('M', s)
* var m = new M({ d: Date('1969-12-31') })
* const s = new Schema({ d: { type: Date, min: Date('1970-01-01') })
* const M = db.model('M', s)
* const m = new M({ d: Date('1969-12-31') })
* m.save(function (err) {
* console.error(err) // validator error
* m.d = Date('2014-12-08');
@@ -216,10 +223,10 @@ SchemaDate.prototype.checkRequired = function(value, doc) {
*
* // custom error messages
* // We can also use the special {MIN} token which will be replaced with the invalid value
* var min = [Date('1970-01-01'), 'The value of path `{PATH}` ({VALUE}) is beneath the limit ({MIN}).'];
* var schema = new Schema({ d: { type: Date, min: min })
* var M = mongoose.model('M', schema);
* var s= new M({ d: Date('1969-12-31') });
* const min = [Date('1970-01-01'), 'The value of path `{PATH}` ({VALUE}) is beneath the limit ({MIN}).'];
* const schema = new Schema({ d: { type: Date, min: min })
* const M = mongoose.model('M', schema);
* const s= new M({ d: Date('1969-12-31') });
* s.validate(function (err) {
* console.log(String(err)) // ValidationError: The value of path `d` (1969-12-31) is before the limit (1970-01-01).
* })
@@ -267,9 +274,9 @@ SchemaDate.prototype.min = function(value, message) {
*
* ####Example:
*
* var s = new Schema({ d: { type: Date, max: Date('2014-01-01') })
* var M = db.model('M', s)
* var m = new M({ d: Date('2014-12-08') })
* const s = new Schema({ d: { type: Date, max: Date('2014-01-01') })
* const M = db.model('M', s)
* const m = new M({ d: Date('2014-12-08') })
* m.save(function (err) {
* console.error(err) // validator error
* m.d = Date('2013-12-31');
@@ -278,10 +285,10 @@ SchemaDate.prototype.min = function(value, message) {
*
* // custom error messages
* // We can also use the special {MAX} token which will be replaced with the invalid value
* var max = [Date('2014-01-01'), 'The value of path `{PATH}` ({VALUE}) exceeds the limit ({MAX}).'];
* var schema = new Schema({ d: { type: Date, max: max })
* var M = mongoose.model('M', schema);
* var s= new M({ d: Date('2014-12-08') });
* const max = [Date('2014-01-01'), 'The value of path `{PATH}` ({VALUE}) exceeds the limit ({MAX}).'];
* const schema = new Schema({ d: { type: Date, max: max })
* const M = mongoose.model('M', schema);
* const s= new M({ d: Date('2014-12-08') });
* s.validate(function (err) {
* console.log(String(err)) // ValidationError: The value of path `d` (2014-12-08) exceeds the limit (2014-01-01).
* })
@@ -332,9 +339,15 @@ SchemaDate.prototype.max = function(value, message) {
*/
SchemaDate.prototype.cast = function(value) {
const castDate = typeof this.constructor.cast === 'function' ?
this.constructor.cast() :
SchemaDate.cast();
let castDate;
if (typeof this._castFunction === 'function') {
castDate = this._castFunction;
} else if (typeof this.constructor.cast === 'function') {
castDate = this.constructor.cast();
} else {
castDate = SchemaDate.cast();
}
try {
return castDate(value);
} catch (error) {

View File

@@ -10,10 +10,6 @@ const Decimal128Type = require('../types/decimal128');
const castDecimal128 = require('../cast/decimal128');
const utils = require('../utils');
const populateModelSymbol = require('../helpers/symbols').populateModelSymbol;
let Document;
/**
* Decimal128 SchemaType constructor.
*
@@ -97,18 +93,24 @@ Decimal128.cast = function cast(caster) {
return this._cast;
}
if (caster === false) {
caster = v => {
if (v != null && !(v instanceof Decimal128Type)) {
throw new Error();
}
return v;
};
caster = this._defaultCaster;
}
this._cast = caster;
return this._cast;
};
/*!
* ignore
*/
Decimal128._defaultCaster = v => {
if (v != null && !(v instanceof Decimal128Type)) {
throw new Error();
}
return v;
};
/*!
* ignore
*/
@@ -162,49 +164,22 @@ Decimal128.prototype.checkRequired = function checkRequired(value, doc) {
Decimal128.prototype.cast = function(value, doc, init) {
if (SchemaType._isRef(this, value, doc, init)) {
// wait! we may need to cast this to a document
if (value === null || value === undefined) {
return value;
}
// lazy load
Document || (Document = require('./../document'));
if (value instanceof Document) {
value.$__.wasPopulated = true;
return value;
}
// setting a populated path
if (value instanceof Decimal128Type) {
return value;
} else if (Buffer.isBuffer(value) || !utils.isObject(value)) {
throw new CastError('Decimal128', value, this.path, null, this);
}
// Handle the case where user directly sets a populated
// path to a plain object; cast to the Model used in
// the population query.
const path = doc.$__fullPath(this.path);
const owner = doc.ownerDocument ? doc.ownerDocument() : doc;
const pop = owner.populated(path, true);
let ret = value;
if (!doc.$__.populated ||
!doc.$__.populated[path] ||
!doc.$__.populated[path].options ||
!doc.$__.populated[path].options.options ||
!doc.$__.populated[path].options.options.lean) {
ret = new pop.options[populateModelSymbol](value);
ret.$__.wasPopulated = true;
}
return ret;
return this._castRef(value, doc, init);
}
let castDecimal128;
if (typeof this._castFunction === 'function') {
castDecimal128 = this._castFunction;
} else if (typeof this.constructor.cast === 'function') {
castDecimal128 = this.constructor.cast();
} else {
castDecimal128 = Decimal128.cast();
}
const castDecimal128 = typeof this.constructor.cast === 'function' ?
this.constructor.cast() :
Decimal128.cast();
try {
return castDecimal128(value);
} catch (error) {

View File

@@ -18,6 +18,7 @@ const util = require('util');
const utils = require('../utils');
const getConstructor = require('../helpers/discriminator/getConstructor');
const arrayAtomicsSymbol = require('../helpers/symbols').arrayAtomicsSymbol;
const arrayPathSymbol = require('../helpers/symbols').arrayPathSymbol;
const documentArrayParent = require('../helpers/symbols').documentArrayParent;
@@ -251,6 +252,11 @@ DocumentArrayPath.prototype.doValidate = function(array, fn, scope, options) {
doc = array[i] = new Constructor(doc, array, undefined, undefined, i);
}
if (options != null && options.validateModifiedOnly && !doc.isModified()) {
--count || fn(error);
continue;
}
doc.$__validate(callback);
}
}
@@ -267,7 +273,7 @@ DocumentArrayPath.prototype.doValidate = function(array, fn, scope, options) {
* @api private
*/
DocumentArrayPath.prototype.doValidateSync = function(array, scope) {
DocumentArrayPath.prototype.doValidateSync = function(array, scope, options) {
const schemaTypeError = SchemaType.prototype.doValidateSync.call(this, array, scope);
if (schemaTypeError != null) {
schemaTypeError.$isArrayValidatorError = true;
@@ -299,6 +305,10 @@ DocumentArrayPath.prototype.doValidateSync = function(array, scope) {
doc = array[i] = new Constructor(doc, array, undefined, undefined, i);
}
if (options != null && options.validateModifiedOnly && !doc.isModified()) {
continue;
}
const subdocValidateError = doc.validateSync();
if (subdocValidateError && resultError == null) {
@@ -361,6 +371,11 @@ DocumentArrayPath.prototype.cast = function(value, doc, init, prev, options) {
// lazy load
MongooseDocumentArray || (MongooseDocumentArray = require('../types/documentarray'));
// Skip casting if `value` is the same as the previous value, no need to cast. See gh-9266
if (value != null && value[arrayPathSymbol] != null && value === prev) {
return value;
}
let selected;
let subdoc;
const _opts = { transform: false, virtuals: false };
@@ -387,11 +402,16 @@ DocumentArrayPath.prototype.cast = function(value, doc, init, prev, options) {
value = new MongooseDocumentArray(value, this.path, doc);
}
if (options.arrayPath != null) {
value[arrayPathSymbol] = options.arrayPath;
if (prev != null) {
value[arrayAtomicsSymbol] = prev[arrayAtomicsSymbol] || {};
}
if (options.arrayPathIndex != null) {
value[arrayPathSymbol] = this.path + '.' + options.arrayPathIndex;
}
const len = value.length;
const initDocumentOptions = { skipId: true, willInit: true };
for (let i = 0; i < len; ++i) {
if (!value[i]) {
@@ -424,7 +444,7 @@ DocumentArrayPath.prototype.cast = function(value, doc, init, prev, options) {
selected = true;
}
subdoc = new Constructor(null, value, true, selected, i);
subdoc = new Constructor(null, value, initDocumentOptions, selected, i);
value[i] = subdoc.init(value[i]);
} else {
if (prev && typeof prev.id === 'function') {
@@ -473,6 +493,14 @@ DocumentArrayPath.prototype.clone = function() {
return schematype;
};
/*!
* ignore
*/
DocumentArrayPath.prototype.applyGetters = function(value, scope) {
return SchemaType.prototype.applyGetters.call(this, value, scope);
};
/*!
* Scopes paths selected in a query to this array.
* Necessary for proper default application of subdocument values.
@@ -513,6 +541,26 @@ function scopePaths(array, fields, init) {
return hasKeys && selected || undefined;
}
/**
* Sets a default option for all DocumentArray instances.
*
* ####Example:
*
* // Make all numbers have option `min` equal to 0.
* mongoose.Schema.DocumentArray.set('_id', false);
*
* @param {String} option - The option you'd like to set the value for
* @param {*} value - value for option
* @return {undefined}
* @function set
* @static
* @api public
*/
DocumentArrayPath.defaultOptions = {};
DocumentArrayPath.set = SchemaType.set;
/*!
* Module exports.
*/

View File

@@ -26,23 +26,37 @@ class Map extends SchemaType {
return val;
}
const path = this.path;
if (init) {
const map = new MongooseMap({}, this.path, doc, this.$__schemaType);
const map = new MongooseMap({}, path, doc, this.$__schemaType);
if (val instanceof global.Map) {
for (const key of val.keys()) {
map.$init(key, map.$__schemaType.cast(val.get(key), doc, true));
let _val = val.get(key);
if (_val == null) {
_val = map.$__schemaType._castNullish(_val);
} else {
_val = map.$__schemaType.cast(_val, doc, true, null, { path: path + '.' + key });
}
map.$init(key, _val);
}
} else {
for (const key of Object.keys(val)) {
map.$init(key, map.$__schemaType.cast(val[key], doc, true));
let _val = val[key];
if (_val == null) {
_val = map.$__schemaType._castNullish(_val);
} else {
_val = map.$__schemaType.cast(_val, doc, true, null, { path: path + '.' + key });
}
map.$init(key, _val);
}
}
return map;
}
return new MongooseMap(val, this.path, doc, this.$__schemaType);
return new MongooseMap(val, path, doc, this.$__schemaType);
}
clone() {

View File

@@ -7,6 +7,7 @@
const SchemaType = require('../schematype');
const symbols = require('./symbols');
const isObject = require('../helpers/isObject');
const utils = require('../utils');
/**
* Mixed SchemaType constructor.
@@ -103,6 +104,9 @@ Mixed.set = SchemaType.set;
*/
Mixed.prototype.cast = function(val) {
if (val instanceof Error) {
return utils.errorToPOJO(val);
}
return val;
};

View File

@@ -11,10 +11,7 @@ const castNumber = require('../cast/number');
const handleBitwiseOperator = require('./operators/bitwise');
const utils = require('../utils');
const populateModelSymbol = require('../helpers/symbols').populateModelSymbol;
const CastError = SchemaType.CastError;
let Document;
/**
* Number SchemaType constructor.
@@ -103,18 +100,24 @@ SchemaNumber.cast = function cast(caster) {
return this._cast;
}
if (caster === false) {
caster = v => {
if (typeof v !== 'number') {
throw new Error();
}
return v;
};
caster = this._defaultCaster;
}
this._cast = caster;
return this._cast;
};
/*!
* ignore
*/
SchemaNumber._defaultCaster = v => {
if (typeof v !== 'number') {
throw new Error();
}
return v;
};
/**
* This schema type's name, to defend against minifiers that mangle
* function names.
@@ -179,9 +182,9 @@ SchemaNumber.prototype.checkRequired = function checkRequired(value, doc) {
*
* ####Example:
*
* var s = new Schema({ n: { type: Number, min: 10 })
* var M = db.model('M', s)
* var m = new M({ n: 9 })
* const s = new Schema({ n: { type: Number, min: 10 })
* const M = db.model('M', s)
* const m = new M({ n: 9 })
* m.save(function (err) {
* console.error(err) // validator error
* m.n = 10;
@@ -190,10 +193,10 @@ SchemaNumber.prototype.checkRequired = function checkRequired(value, doc) {
*
* // custom error messages
* // We can also use the special {MIN} token which will be replaced with the invalid value
* var min = [10, 'The value of path `{PATH}` ({VALUE}) is beneath the limit ({MIN}).'];
* var schema = new Schema({ n: { type: Number, min: min })
* var M = mongoose.model('Measurement', schema);
* var s= new M({ n: 4 });
* const min = [10, 'The value of path `{PATH}` ({VALUE}) is beneath the limit ({MIN}).'];
* const schema = new Schema({ n: { type: Number, min: min })
* const M = mongoose.model('Measurement', schema);
* const s= new M({ n: 4 });
* s.validate(function (err) {
* console.log(String(err)) // ValidationError: The value of path `n` (4) is beneath the limit (10).
* })
@@ -233,9 +236,9 @@ SchemaNumber.prototype.min = function(value, message) {
*
* ####Example:
*
* var s = new Schema({ n: { type: Number, max: 10 })
* var M = db.model('M', s)
* var m = new M({ n: 11 })
* const s = new Schema({ n: { type: Number, max: 10 })
* const M = db.model('M', s)
* const m = new M({ n: 11 })
* m.save(function (err) {
* console.error(err) // validator error
* m.n = 10;
@@ -244,10 +247,10 @@ SchemaNumber.prototype.min = function(value, message) {
*
* // custom error messages
* // We can also use the special {MAX} token which will be replaced with the invalid value
* var max = [10, 'The value of path `{PATH}` ({VALUE}) exceeds the limit ({MAX}).'];
* var schema = new Schema({ n: { type: Number, max: max })
* var M = mongoose.model('Measurement', schema);
* var s= new M({ n: 4 });
* const max = [10, 'The value of path `{PATH}` ({VALUE}) exceeds the limit ({MAX}).'];
* const schema = new Schema({ n: { type: Number, max: max })
* const M = mongoose.model('Measurement', schema);
* const s= new M({ n: 4 });
* s.validate(function (err) {
* console.log(String(err)) // ValidationError: The value of path `n` (4) exceeds the limit (10).
* })
@@ -287,10 +290,10 @@ SchemaNumber.prototype.max = function(value, message) {
*
* ####Example:
*
* var s = new Schema({ n: { type: Number, enum: [1, 2, 3] });
* var M = db.model('M', s);
* const s = new Schema({ n: { type: Number, enum: [1, 2, 3] });
* const M = db.model('M', s);
*
* var m = new M({ n: 4 });
* const m = new M({ n: 4 });
* await m.save(); // throws validation error
*
* m.n = 3;
@@ -310,8 +313,13 @@ SchemaNumber.prototype.enum = function(values, message) {
}, this);
}
if (!Array.isArray(values)) {
values = Array.prototype.slice.call(arguments);
if (utils.isObject(values)) {
values = utils.object.vals(values);
} else {
values = Array.prototype.slice.call(arguments);
}
message = MongooseError.messages.Number.enum;
}
@@ -339,45 +347,26 @@ SchemaNumber.prototype.enum = function(values, message) {
SchemaNumber.prototype.cast = function(value, doc, init) {
if (SchemaType._isRef(this, value, doc, init)) {
// wait! we may need to cast this to a document
if (value === null || value === undefined) {
return value;
}
// lazy load
Document || (Document = require('./../document'));
if (value instanceof Document) {
value.$__.wasPopulated = true;
return value;
}
// setting a populated path
if (typeof value === 'number') {
return value;
} else if (Buffer.isBuffer(value) || !utils.isObject(value)) {
throw new CastError('Number', value, this.path, null, this);
}
// Handle the case where user directly sets a populated
// path to a plain object; cast to the Model used in
// the population query.
const path = doc.$__fullPath(this.path);
const owner = doc.ownerDocument ? doc.ownerDocument() : doc;
const pop = owner.populated(path, true);
const ret = new pop.options[populateModelSymbol](value);
ret.$__.wasPopulated = true;
return ret;
return this._castRef(value, doc, init);
}
const val = value && typeof value._id !== 'undefined' ?
value._id : // documents
value;
const castNumber = typeof this.constructor.cast === 'function' ?
this.constructor.cast() :
SchemaNumber.cast();
let castNumber;
if (typeof this._castFunction === 'function') {
castNumber = this._castFunction;
} else if (typeof this.constructor.cast === 'function') {
castNumber = this.constructor.cast();
} else {
castNumber = SchemaNumber.cast();
}
try {
return castNumber(val);
} catch (err) {

View File

@@ -7,11 +7,10 @@
const SchemaObjectIdOptions = require('../options/SchemaObjectIdOptions');
const SchemaType = require('../schematype');
const castObjectId = require('../cast/objectid');
const getConstructorName = require('../helpers/getConstructorName');
const oid = require('../types/objectid');
const utils = require('../utils');
const populateModelSymbol = require('../helpers/symbols').populateModelSymbol;
const CastError = SchemaType.CastError;
let Document;
@@ -151,18 +150,24 @@ ObjectId.cast = function cast(caster) {
return this._cast;
}
if (caster === false) {
caster = v => {
if (!(v instanceof oid)) {
throw new Error(v + ' is not an instance of ObjectId');
}
return v;
};
caster = this._defaultCaster;
}
this._cast = caster;
return this._cast;
};
/*!
* ignore
*/
ObjectId._defaultCaster = v => {
if (!(v instanceof oid)) {
throw new Error(v + ' is not an instance of ObjectId');
}
return v;
};
/**
* Override the function the required validator uses to check whether a string
* passes the `required` check.
@@ -219,50 +224,24 @@ ObjectId.prototype.checkRequired = function checkRequired(value, doc) {
ObjectId.prototype.cast = function(value, doc, init) {
if (SchemaType._isRef(this, value, doc, init)) {
// wait! we may need to cast this to a document
if (value === null || value === undefined) {
return value;
}
// lazy load
Document || (Document = require('./../document'));
if (value instanceof Document) {
value.$__.wasPopulated = true;
return value;
}
// setting a populated path
if (value instanceof oid) {
return value;
} else if ((value.constructor.name || '').toLowerCase() === 'objectid') {
} else if ((getConstructorName(value) || '').toLowerCase() === 'objectid') {
return new oid(value.toHexString());
} else if (Buffer.isBuffer(value) || !utils.isObject(value)) {
throw new CastError('ObjectId', value, this.path, null, this);
}
// Handle the case where user directly sets a populated
// path to a plain object; cast to the Model used in
// the population query.
const path = doc.$__fullPath(this.path);
const owner = doc.ownerDocument ? doc.ownerDocument() : doc;
const pop = owner.populated(path, true);
let ret = value;
if (!doc.$__.populated ||
!doc.$__.populated[path] ||
!doc.$__.populated[path].options ||
!doc.$__.populated[path].options.options ||
!doc.$__.populated[path].options.options.lean) {
ret = new pop.options[populateModelSymbol](value);
ret.$__.wasPopulated = true;
}
return ret;
return this._castRef(value, doc, init);
}
let castObjectId;
if (typeof this._castFunction === 'function') {
castObjectId = this._castFunction;
} else if (typeof this.constructor.cast === 'function') {
castObjectId = this.constructor.cast();
} else {
castObjectId = ObjectId.cast();
}
const castObjectId = typeof this.constructor.cast === 'function' ?
this.constructor.cast() :
ObjectId.cast();
try {
return castObjectId(value);
} catch (error) {

View File

@@ -5,8 +5,15 @@
*/
module.exports = function(val) {
if (Array.isArray(val)) {
if (!val.every(v => typeof v === 'number' || typeof v === 'string')) {
throw new Error('$type array values must be strings or numbers');
}
return val;
}
if (typeof val !== 'number' && typeof val !== 'string') {
throw new Error('$type parameter must be number or string');
throw new Error('$type parameter must be number, string, or array of numbers and strings');
}
return val;

View File

@@ -10,10 +10,7 @@ const SchemaStringOptions = require('../options/SchemaStringOptions');
const castString = require('../cast/string');
const utils = require('../utils');
const populateModelSymbol = require('../helpers/symbols').populateModelSymbol;
const CastError = SchemaType.CastError;
let Document;
/**
* String SchemaType constructor.
@@ -86,18 +83,24 @@ SchemaString.cast = function cast(caster) {
return this._cast;
}
if (caster === false) {
caster = v => {
if (v != null && typeof v !== 'string') {
throw new Error();
}
return v;
};
caster = this._defaultCaster;
}
this._cast = caster;
return this._cast;
};
/*!
* ignore
*/
SchemaString._defaultCaster = v => {
if (v != null && typeof v !== 'string') {
throw new Error();
}
return v;
};
/**
* Attaches a getter for all String instances.
*
@@ -171,10 +174,10 @@ SchemaString.checkRequired = SchemaType.checkRequired;
*
* ####Example:
*
* var states = ['opening', 'open', 'closing', 'closed']
* var s = new Schema({ state: { type: String, enum: states }})
* var M = db.model('M', s)
* var m = new M({ state: 'invalid' })
* const states = ['opening', 'open', 'closing', 'closed']
* const s = new Schema({ state: { type: String, enum: states }})
* const M = db.model('M', s)
* const m = new M({ state: 'invalid' })
* m.save(function (err) {
* console.error(String(err)) // ValidationError: `invalid` is not a valid enum value for path `state`.
* m.state = 'open'
@@ -182,13 +185,13 @@ SchemaString.checkRequired = SchemaType.checkRequired;
* })
*
* // or with custom error messages
* var enum = {
* const enum = {
* values: ['opening', 'open', 'closing', 'closed'],
* message: 'enum validator failed for path `{PATH}` with value `{VALUE}`'
* }
* var s = new Schema({ state: { type: String, enum: enum })
* var M = db.model('M', s)
* var m = new M({ state: 'invalid' })
* const s = new Schema({ state: { type: String, enum: enum })
* const M = db.model('M', s)
* const m = new M({ state: 'invalid' })
* m.save(function (err) {
* console.error(String(err)) // ValidationError: enum validator failed for path `state` with value `invalid`
* m.state = 'open'
@@ -217,8 +220,13 @@ SchemaString.prototype.enum = function() {
let errorMessage;
if (utils.isObject(arguments[0])) {
values = arguments[0].values;
errorMessage = arguments[0].message;
if (Array.isArray(arguments[0].values)) {
values = arguments[0].values;
errorMessage = arguments[0].message;
} else {
values = utils.object.vals(arguments[0]);
errorMessage = MongooseError.messages.String.enum;
}
} else {
values = arguments;
errorMessage = MongooseError.messages.String.enum;
@@ -249,9 +257,9 @@ SchemaString.prototype.enum = function() {
*
* ####Example:
*
* var s = new Schema({ email: { type: String, lowercase: true }})
* var M = db.model('M', s);
* var m = new M({ email: 'SomeEmail@example.COM' });
* const s = new Schema({ email: { type: String, lowercase: true }})
* const M = db.model('M', s);
* const m = new M({ email: 'SomeEmail@example.COM' });
* console.log(m.email) // someemail@example.com
* M.find({ email: 'SomeEmail@example.com' }); // Queries by 'someemail@example.com'
*
@@ -287,9 +295,9 @@ SchemaString.prototype.lowercase = function(shouldApply) {
*
* ####Example:
*
* var s = new Schema({ caps: { type: String, uppercase: true }})
* var M = db.model('M', s);
* var m = new M({ caps: 'an example' });
* const s = new Schema({ caps: { type: String, uppercase: true }})
* const M = db.model('M', s);
* const m = new M({ caps: 'an example' });
* console.log(m.caps) // AN EXAMPLE
* M.find({ caps: 'an example' }) // Matches documents where caps = 'AN EXAMPLE'
*
@@ -325,11 +333,11 @@ SchemaString.prototype.uppercase = function(shouldApply) {
*
* ####Example:
*
* var s = new Schema({ name: { type: String, trim: true }});
* var M = db.model('M', s);
* var string = ' some name ';
* const s = new Schema({ name: { type: String, trim: true }});
* const M = db.model('M', s);
* const string = ' some name ';
* console.log(string.length); // 11
* var m = new M({ name: string });
* const m = new M({ name: string });
* console.log(m.name.length); // 9
*
* // Equivalent to `findOne({ name: string.trim() })`
@@ -365,9 +373,9 @@ SchemaString.prototype.trim = function(shouldTrim) {
*
* ####Example:
*
* var schema = new Schema({ postalCode: { type: String, minlength: 5 })
* var Address = db.model('Address', schema)
* var address = new Address({ postalCode: '9512' })
* const schema = new Schema({ postalCode: { type: String, minlength: 5 })
* const Address = db.model('Address', schema)
* const address = new Address({ postalCode: '9512' })
* address.save(function (err) {
* console.error(err) // validator error
* address.postalCode = '95125';
@@ -376,10 +384,10 @@ SchemaString.prototype.trim = function(shouldTrim) {
*
* // custom error messages
* // We can also use the special {MINLENGTH} token which will be replaced with the minimum allowed length
* var minlength = [5, 'The value of path `{PATH}` (`{VALUE}`) is shorter than the minimum allowed length ({MINLENGTH}).'];
* var schema = new Schema({ postalCode: { type: String, minlength: minlength })
* var Address = mongoose.model('Address', schema);
* var address = new Address({ postalCode: '9512' });
* const minlength = [5, 'The value of path `{PATH}` (`{VALUE}`) is shorter than the minimum allowed length ({MINLENGTH}).'];
* const schema = new Schema({ postalCode: { type: String, minlength: minlength })
* const Address = mongoose.model('Address', schema);
* const address = new Address({ postalCode: '9512' });
* address.validate(function (err) {
* console.log(String(err)) // ValidationError: The value of path `postalCode` (`9512`) is shorter than the minimum length (5).
* })
@@ -414,14 +422,16 @@ SchemaString.prototype.minlength = function(value, message) {
return this;
};
SchemaString.prototype.minLength = SchemaString.prototype.minlength;
/**
* Sets a maximum length validator.
*
* ####Example:
*
* var schema = new Schema({ postalCode: { type: String, maxlength: 9 })
* var Address = db.model('Address', schema)
* var address = new Address({ postalCode: '9512512345' })
* const schema = new Schema({ postalCode: { type: String, maxlength: 9 })
* const Address = db.model('Address', schema)
* const address = new Address({ postalCode: '9512512345' })
* address.save(function (err) {
* console.error(err) // validator error
* address.postalCode = '95125';
@@ -430,10 +440,10 @@ SchemaString.prototype.minlength = function(value, message) {
*
* // custom error messages
* // We can also use the special {MAXLENGTH} token which will be replaced with the maximum allowed length
* var maxlength = [9, 'The value of path `{PATH}` (`{VALUE}`) exceeds the maximum allowed length ({MAXLENGTH}).'];
* var schema = new Schema({ postalCode: { type: String, maxlength: maxlength })
* var Address = mongoose.model('Address', schema);
* var address = new Address({ postalCode: '9512512345' });
* const maxlength = [9, 'The value of path `{PATH}` (`{VALUE}`) exceeds the maximum allowed length ({MAXLENGTH}).'];
* const schema = new Schema({ postalCode: { type: String, maxlength: maxlength })
* const Address = mongoose.model('Address', schema);
* const address = new Address({ postalCode: '9512512345' });
* address.validate(function (err) {
* console.log(String(err)) // ValidationError: The value of path `postalCode` (`9512512345`) exceeds the maximum allowed length (9).
* })
@@ -468,6 +478,8 @@ SchemaString.prototype.maxlength = function(value, message) {
return this;
};
SchemaString.prototype.maxLength = SchemaString.prototype.maxlength;
/**
* Sets a regexp validator.
*
@@ -475,9 +487,9 @@ SchemaString.prototype.maxlength = function(value, message) {
*
* ####Example:
*
* var s = new Schema({ name: { type: String, match: /^a/ }})
* var M = db.model('M', s)
* var m = new M({ name: 'I am invalid' })
* const s = new Schema({ name: { type: String, match: /^a/ }})
* const M = db.model('M', s)
* const m = new M({ name: 'I am invalid' })
* m.validate(function (err) {
* console.error(String(err)) // "ValidationError: Path `name` is invalid (I am invalid)."
* m.name = 'apples'
@@ -487,17 +499,17 @@ SchemaString.prototype.maxlength = function(value, message) {
* })
*
* // using a custom error message
* var match = [ /\.html$/, "That file doesn't end in .html ({VALUE})" ];
* var s = new Schema({ file: { type: String, match: match }})
* var M = db.model('M', s);
* var m = new M({ file: 'invalid' });
* const match = [ /\.html$/, "That file doesn't end in .html ({VALUE})" ];
* const s = new Schema({ file: { type: String, match: match }})
* const M = db.model('M', s);
* const m = new M({ file: 'invalid' });
* m.validate(function (err) {
* console.log(String(err)) // "ValidationError: That file doesn't end in .html (invalid)"
* })
*
* Empty strings, `undefined`, and `null` values always pass the match validator. If you require these values, enable the `required` validator also.
*
* var s = new Schema({ name: { type: String, match: /^a/, required: true }})
* const s = new Schema({ name: { type: String, match: /^a/, required: true }})
*
* @param {RegExp} regExp regular expression to test against
* @param {String} [message] optional custom error message
@@ -516,6 +528,10 @@ SchemaString.prototype.match = function match(regExp, message) {
return false;
}
// In case RegExp happens to have `/g` flag set, we need to reset the
// `lastIndex`, otherwise `match` will intermittently fail.
regExp.lastIndex = 0;
const ret = ((v != null && v !== '')
? regExp.test(v)
: true);
@@ -565,41 +581,22 @@ SchemaString.prototype.checkRequired = function checkRequired(value, doc) {
SchemaString.prototype.cast = function(value, doc, init) {
if (SchemaType._isRef(this, value, doc, init)) {
// wait! we may need to cast this to a document
if (value === null || value === undefined) {
return value;
}
// lazy load
Document || (Document = require('./../document'));
if (value instanceof Document) {
value.$__.wasPopulated = true;
return value;
}
// setting a populated path
if (typeof value === 'string') {
return value;
} else if (Buffer.isBuffer(value) || !utils.isObject(value)) {
throw new CastError('string', value, this.path, null, this);
}
// Handle the case where user directly sets a populated
// path to a plain object; cast to the Model used in
// the population query.
const path = doc.$__fullPath(this.path);
const owner = doc.ownerDocument ? doc.ownerDocument() : doc;
const pop = owner.populated(path, true);
const ret = new pop.options[populateModelSymbol](value);
ret.$__.wasPopulated = true;
return ret;
return this._castRef(value, doc, init);
}
let castString;
if (typeof this._castFunction === 'function') {
castString = this._castFunction;
} else if (typeof this.constructor.cast === 'function') {
castString = this.constructor.cast();
} else {
castString = SchemaString.cast();
}
const castString = typeof this.constructor.cast === 'function' ?
this.constructor.cast() :
SchemaString.cast();
try {
return castString(value);
} catch (error) {