Updated mongoose

This commit is contained in:
Dobie Wollert
2015-11-24 22:08:58 -08:00
parent 71a05fb732
commit 8b5827c970
618 changed files with 122299 additions and 37754 deletions

View File

@ -2,23 +2,22 @@
* Module dependencies.
*/
var SchemaType = require('../schematype')
, CastError = SchemaType.CastError
, NumberSchema = require('./number')
, Types = {
Boolean: require('./boolean')
, Date: require('./date')
, Number: require('./number')
, String: require('./string')
, ObjectId: require('./objectid')
, Buffer: require('./buffer')
}
, MongooseArray = require('../types').Array
, EmbeddedDoc = require('../types').Embedded
, Mixed = require('./mixed')
, Query = require('../query')
, utils = require('../utils')
, isMongooseObject = utils.isMongooseObject
var SchemaType = require('../schematype'),
CastError = SchemaType.CastError,
Types = {
Boolean: require('./boolean'),
Date: require('./date'),
Number: require('./number'),
String: require('./string'),
ObjectId: require('./objectid'),
Buffer: require('./buffer')
},
MongooseArray = require('../types').Array,
EmbeddedDoc = require('../types').Embedded,
Mixed = require('./mixed'),
cast = require('../cast'),
utils = require('../utils'),
isMongooseObject = utils.isMongooseObject;
/**
* Array SchemaType constructor
@ -30,11 +29,11 @@ var SchemaType = require('../schematype')
* @api private
*/
function SchemaArray (key, cast, options) {
function SchemaArray(key, cast, options) {
if (cast) {
var castOptions = {};
if ('Object' === cast.constructor.name) {
if ('Object' === utils.getFunctionName(cast.constructor)) {
if (cast.type) {
// support { type: Woot }
castOptions = utils.clone(cast); // do not alter user arguments
@ -48,7 +47,7 @@ function SchemaArray (key, cast, options) {
// support { type: 'String' }
var name = 'string' == typeof cast
? cast
: cast.name;
: utils.getFunctionName(cast);
var caster = name in Types
? Types[name]
@ -61,28 +60,36 @@ function SchemaArray (key, cast, options) {
}
}
SchemaType.call(this, key, options);
SchemaType.call(this, key, options, 'Array');
var self = this
, defaultArr
, fn;
var self = this,
defaultArr,
fn;
if (this.defaultValue) {
defaultArr = this.defaultValue;
fn = 'function' == typeof defaultArr;
}
this.default(function(){
this.default(function() {
var arr = fn ? defaultArr() : defaultArr || [];
return new MongooseArray(arr, self.path, this);
});
};
}
/**
* This schema type's name, to defend against minifiers that mangle
* function names.
*
* @api private
*/
SchemaArray.schemaName = 'Array';
/*!
* Inherits from SchemaType.
*/
SchemaArray.prototype.__proto__ = SchemaType.prototype;
SchemaArray.prototype = Object.create( SchemaType.prototype );
SchemaArray.prototype.constructor = SchemaArray;
/**
* Check required
@ -91,7 +98,7 @@ SchemaArray.prototype.__proto__ = SchemaType.prototype;
* @api private
*/
SchemaArray.prototype.checkRequired = function (value) {
SchemaArray.prototype.checkRequired = function(value) {
return !!(value && value.length);
};
@ -103,7 +110,7 @@ SchemaArray.prototype.checkRequired = function (value) {
* @api private
*/
SchemaArray.prototype.applyGetters = function (value, scope) {
SchemaArray.prototype.applyGetters = function(value, scope) {
if (this.caster.options && this.caster.options.ref) {
// means the object id was populated
return value;
@ -113,7 +120,7 @@ SchemaArray.prototype.applyGetters = function (value, scope) {
};
/**
* Casts contents
* Casts values for set().
*
* @param {Object} value
* @param {Document} doc document that triggers the casting
@ -121,15 +128,27 @@ SchemaArray.prototype.applyGetters = function (value, scope) {
* @api private
*/
SchemaArray.prototype.cast = function (value, doc, init) {
SchemaArray.prototype.cast = function(value, doc, init) {
if (Array.isArray(value)) {
if (!(value instanceof MongooseArray)) {
if (!value.length && doc) {
var indexes = doc.schema.indexedPaths();
for (var i = 0, l = indexes.length; i < l; ++i) {
var pathIndex = indexes[i][0][this.path];
if ('2dsphere' === pathIndex || '2d' === pathIndex) {
return;
}
}
}
if (!(value && value.isMongooseArray)) {
value = new MongooseArray(value, this.path, doc);
}
if (this.caster) {
try {
for (var i = 0, l = value.length; i < l; i++) {
for (i = 0, l = value.length; i < l; i++) {
value[i] = this.caster.cast(value[i], doc, init);
}
} catch (e) {
@ -140,175 +159,234 @@ SchemaArray.prototype.cast = function (value, doc, init) {
return value;
} else {
// gh-2442: if we're loading this from the db and its not an array, mark
// the whole array as modified.
if (!!doc && !!init) {
doc.markModified(this.path);
}
return this.cast([value], doc, init);
}
};
/**
* Casts contents for queries.
* Casts values for queries.
*
* @param {String} $conditional
* @param {any} [value]
* @api private
*/
SchemaArray.prototype.castForQuery = function ($conditional, value) {
var handler
, val;
SchemaArray.prototype.castForQuery = function($conditional, value) {
var handler,
val;
if (arguments.length === 2) {
handler = this.$conditionalHandlers[$conditional];
if (!handler)
if (!handler) {
throw new Error("Can't use " + $conditional + " with Array.");
}
val = handler.call(this, value);
} else {
val = $conditional;
var proto = this.casterConstructor.prototype;
var method = proto.castForQuery || proto.cast;
var caster = this.caster;
if (Array.isArray(val)) {
val = val.map(function (v) {
if (method) v = method.call(caster, v);
return isMongooseObject(v)
? v.toObject()
: v;
if (Array.isArray(val)) {
val = val.map(function(v) {
if (utils.isObject(v) && v.$elemMatch) {
return v;
}
if (method) v = method.call(caster, v);
return isMongooseObject(v) ?
v.toObject({ virtuals: false }) :
v;
});
} else if (method) {
val = method.call(caster, val);
}
}
return val && isMongooseObject(val)
? val.toObject()
: val;
return val && isMongooseObject(val) ?
val.toObject({ virtuals: false }) :
val;
};
/*!
* @ignore
*
* $atomic cast helpers
*/
function castToNumber (val) {
function castToNumber(val) {
return Types.Number.prototype.cast.call(this, val);
}
function castArray (arr, self) {
function castArraysOfNumbers(arr, self) {
self || (self = this);
arr.forEach(function (v, i) {
arr.forEach(function(v, i) {
if (Array.isArray(v)) {
castArray(v, self);
castArraysOfNumbers(v, self);
} else {
arr[i] = castToNumber.call(self, v);
}
});
}
SchemaArray.prototype.$conditionalHandlers = {
'$all': function handle$all (val) {
if (!Array.isArray(val)) {
val = [val];
function cast$near(val) {
if (Array.isArray(val)) {
castArraysOfNumbers(val, this);
return val;
}
if (val && val.$geometry) {
return cast$geometry(val, this);
}
return SchemaArray.prototype.castForQuery.call(this, val);
}
function cast$geometry(val, self) {
switch (val.$geometry.type) {
case 'Polygon':
case 'LineString':
case 'Point':
castArraysOfNumbers(val.$geometry.coordinates, self);
break;
default:
// ignore unknowns
break;
}
if (val.$maxDistance) {
val.$maxDistance = castToNumber.call(self, val.$maxDistance);
}
return val;
}
function cast$within(val) {
var self = this;
if (val.$maxDistance) {
val.$maxDistance = castToNumber.call(self, val.$maxDistance);
}
if (val.$box || val.$polygon) {
var type = val.$box ? '$box' : '$polygon';
val[type].forEach(function(arr) {
if (!Array.isArray(arr)) {
var msg = 'Invalid $within $box argument. '
+ 'Expected an array, received ' + arr;
throw new TypeError(msg);
}
arr.forEach(function(v, i) {
arr[i] = castToNumber.call(this, v);
});
});
} else if (val.$center || val.$centerSphere) {
type = val.$center ? '$center' : '$centerSphere';
val[type].forEach(function(item, i) {
if (Array.isArray(item)) {
item.forEach(function(v, j) {
item[j] = castToNumber.call(this, v);
});
} else {
val[type][i] = castToNumber.call(this, item);
}
});
} else if (val.$geometry) {
cast$geometry(val, this);
}
val = val.map(function (v) {
if (v && 'Object' === v.constructor.name) {
var o = {};
o[this.path] = v;
var query = new Query(o);
query.cast(this.casterConstructor);
return query._conditions[this.path];
}
return v;
}, this);
return val;
}
return this.castForQuery(val);
function cast$all(val) {
if (!Array.isArray(val)) {
val = [val];
}
val = val.map(function(v) {
if (utils.isObject(v)) {
var o = {};
o[this.path] = v;
return cast(this.casterConstructor.schema, o)[this.path];
}
, '$elemMatch': function (val) {
if (val.$in) {
val.$in = this.castForQuery('$in', val.$in);
return val;
}
return v;
}, this);
var query = new Query(val);
query.cast(this.casterConstructor);
return query._conditions;
return this.castForQuery(val);
}
function cast$elemMatch(val) {
var keys = Object.keys(val);
var numKeys = keys.length;
var key;
var value;
for (var i = 0; i < numKeys; ++i) {
key = keys[i];
value = val[key];
if (key.indexOf('$') === 0 && value) {
val[key] = this.castForQuery(key, value);
}
, '$size': castToNumber
, '$ne': SchemaArray.prototype.castForQuery
, '$in': SchemaArray.prototype.castForQuery
, '$nin': SchemaArray.prototype.castForQuery
, '$regex': SchemaArray.prototype.castForQuery
, '$options': String
, '$near': SchemaArray.prototype.castForQuery
, '$nearSphere': SchemaArray.prototype.castForQuery
, '$gt': SchemaArray.prototype.castForQuery
, '$gte': SchemaArray.prototype.castForQuery
, '$lt': SchemaArray.prototype.castForQuery
, '$lte': SchemaArray.prototype.castForQuery
, '$within': function (val) {
var self = this;
}
if (val.$maxDistance) {
val.$maxDistance = castToNumber.call(this, val.$maxDistance);
}
return cast(this.casterConstructor.schema, val);
}
if (val.$box || val.$polygon) {
var type = val.$box ? '$box' : '$polygon';
val[type].forEach(function (arr) {
if (!Array.isArray(arr)) {
var msg = 'Invalid $within $box argument. '
+ 'Expected an array, received ' + arr;
throw new TypeError(msg);
}
arr.forEach(function (v, i) {
arr[i] = castToNumber.call(this, v);
});
})
} else if (val.$center || val.$centerSphere) {
var type = val.$center ? '$center' : '$centerSphere';
val[type].forEach(function (item, i) {
if (Array.isArray(item)) {
item.forEach(function (v, j) {
item[j] = castToNumber.call(this, v);
});
} else {
val[type][i] = castToNumber.call(this, item);
}
})
} else if (val.$geometry) {
switch (val.$geometry.type) {
case 'Polygon':
case 'LineString':
case 'Point':
val.$geometry.coordinates.forEach(castArray);
break;
default:
// ignore unknowns
break;
}
}
function cast$geoIntersects(val) {
var geo = val.$geometry;
if (!geo) return;
return val;
}
, '$geoIntersects': function (val) {
var geo = val.$geometry;
if (!geo) return;
cast$geometry(val, this);
return val;
}
switch (val.$geometry.type) {
case 'Polygon':
case 'LineString':
case 'Point':
val.$geometry.coordinates.forEach(castArray);
break;
default:
// ignore unknowns
break;
}
var handle = SchemaArray.prototype.$conditionalHandlers = {};
return val;
}
, '$maxDistance': castToNumber
handle.$all = cast$all;
handle.$options = String;
handle.$elemMatch = cast$elemMatch;
handle.$geoIntersects = cast$geoIntersects;
handle.$or = handle.$and = function(val) {
if (!Array.isArray(val)) {
throw new TypeError('conditional $or/$and require array');
}
var ret = [];
for (var i = 0; i < val.length; ++i) {
ret.push(cast(this.casterConstructor.schema, val[i]));
}
return ret;
};
handle.$near =
handle.$nearSphere = cast$near;
handle.$within =
handle.$geoWithin = cast$within;
handle.$size =
handle.$maxDistance = castToNumber;
handle.$eq =
handle.$gt =
handle.$gte =
handle.$in =
handle.$lt =
handle.$lte =
handle.$ne =
handle.$nin =
handle.$regex = SchemaArray.prototype.castForQuery;
/*!
* Module exports.
*/

View File

@ -2,6 +2,8 @@
* Module dependencies.
*/
var utils = require('../utils');
var SchemaType = require('../schematype');
/**
@ -13,14 +15,23 @@ var SchemaType = require('../schematype');
* @api private
*/
function SchemaBoolean (path, options) {
SchemaType.call(this, path, options);
};
function SchemaBoolean(path, options) {
SchemaType.call(this, path, options, 'Boolean');
}
/**
* This schema type's name, to defend against minifiers that mangle
* function names.
*
* @api private
*/
SchemaBoolean.schemaName = 'Boolean';
/*!
* Inherits from SchemaType.
*/
SchemaBoolean.prototype.__proto__ = SchemaType.prototype;
SchemaBoolean.prototype = Object.create( SchemaType.prototype );
SchemaBoolean.prototype.constructor = SchemaBoolean;
/**
* Required validator
@ -28,7 +39,7 @@ SchemaBoolean.prototype.__proto__ = SchemaType.prototype;
* @api private
*/
SchemaBoolean.prototype.checkRequired = function (value) {
SchemaBoolean.prototype.checkRequired = function(value) {
return value === true || value === false;
};
@ -39,28 +50,16 @@ SchemaBoolean.prototype.checkRequired = function (value) {
* @api private
*/
SchemaBoolean.prototype.cast = function (value) {
SchemaBoolean.prototype.cast = function(value) {
if (null === value) return value;
if ('0' === value) return false;
if ('true' === value) return true;
if ('false' === value) return false;
return !! value;
}
return !!value;
};
/*!
* ignore
*/
function handleArray (val) {
var self = this;
return val.map(function (m) {
return self.cast(m);
});
}
SchemaBoolean.$conditionalHandlers = {
'$in': handleArray
}
SchemaBoolean.$conditionalHandlers =
utils.options(SchemaType.prototype.$conditionalHandlers, {});
/**
* Casts contents for queries.
@ -70,7 +69,7 @@ SchemaBoolean.$conditionalHandlers = {
* @api private
*/
SchemaBoolean.prototype.castForQuery = function ($conditional, val) {
SchemaBoolean.prototype.castForQuery = function($conditional, val) {
var handler;
if (2 === arguments.length) {
handler = SchemaBoolean.$conditionalHandlers[$conditional];

View File

@ -2,13 +2,14 @@
* Module dependencies.
*/
var SchemaType = require('../schematype')
, CastError = SchemaType.CastError
, MongooseBuffer = require('../types').Buffer
, Binary = MongooseBuffer.Binary
, Query = require('../query')
, utils = require('../utils')
, Document
var utils = require('../utils');
var MongooseBuffer = require('../types').Buffer;
var SchemaType = require('../schematype');
var Binary = MongooseBuffer.Binary;
var CastError = SchemaType.CastError;
var Document;
/**
* Buffer SchemaType constructor
@ -19,15 +20,23 @@ var SchemaType = require('../schematype')
* @api private
*/
function SchemaBuffer (key, options) {
function SchemaBuffer(key, options) {
SchemaType.call(this, key, options, 'Buffer');
};
}
/**
* This schema type's name, to defend against minifiers that mangle
* function names.
*
* @api private
*/
SchemaBuffer.schemaName = 'Buffer';
/*!
* Inherits from SchemaType.
*/
SchemaBuffer.prototype.__proto__ = SchemaType.prototype;
SchemaBuffer.prototype = Object.create( SchemaType.prototype );
SchemaBuffer.prototype.constructor = SchemaBuffer;
/**
* Check required
@ -35,7 +44,7 @@ SchemaBuffer.prototype.__proto__ = SchemaType.prototype;
* @api private
*/
SchemaBuffer.prototype.checkRequired = function (value, doc) {
SchemaBuffer.prototype.checkRequired = function(value, doc) {
if (SchemaType._isRef(this, value, doc, true)) {
return null != value;
} else {
@ -52,7 +61,8 @@ SchemaBuffer.prototype.checkRequired = function (value, doc) {
* @api private
*/
SchemaBuffer.prototype.cast = function (value, doc, init) {
SchemaBuffer.prototype.cast = function(value, doc, init) {
var ret;
if (SchemaType._isRef(this, value, doc, init)) {
// wait! we may need to cast this to a document
@ -81,7 +91,7 @@ SchemaBuffer.prototype.cast = function (value, doc, init) {
var path = doc.$__fullPath(this.path);
var owner = doc.ownerDocument ? doc.ownerDocument() : doc;
var pop = owner.populated(path, true);
var ret = new pop.options.model(value);
ret = new pop.options.model(value);
ret.$__.wasPopulated = true;
return ret;
}
@ -91,17 +101,22 @@ SchemaBuffer.prototype.cast = function (value, doc, init) {
value = value._id;
}
if (value && value.isMongooseBuffer) {
return value;
}
if (Buffer.isBuffer(value)) {
if (!(value instanceof MongooseBuffer)) {
if (!value || !value.isMongooseBuffer) {
value = new MongooseBuffer(value, [this.path, doc]);
}
return value;
} else if (value instanceof Binary) {
var ret = new MongooseBuffer(value.value(true), [this.path, doc]);
ret = new MongooseBuffer(value.value(true), [this.path, doc]);
if (typeof value.sub_type !== 'number') {
throw new CastError('buffer', value, this.path);
}
ret._subtype = value.sub_type;
// do not override Binary subtypes. users set this
// to whatever they want.
return ret;
}
@ -109,7 +124,7 @@ SchemaBuffer.prototype.cast = function (value, doc, init) {
var type = typeof value;
if ('string' == type || 'number' == type || Array.isArray(value)) {
var ret = new MongooseBuffer(value, [this.path, doc]);
ret = new MongooseBuffer(value, [this.path, doc]);
return ret;
}
@ -119,26 +134,17 @@ SchemaBuffer.prototype.cast = function (value, doc, init) {
/*!
* ignore
*/
function handleSingle (val) {
function handleSingle(val) {
return this.castForQuery(val);
}
function handleArray (val) {
var self = this;
return val.map( function (m) {
return self.castForQuery(m);
SchemaBuffer.prototype.$conditionalHandlers =
utils.options(SchemaType.prototype.$conditionalHandlers, {
'$gt' : handleSingle,
'$gte': handleSingle,
'$lt' : handleSingle,
'$lte': handleSingle
});
}
SchemaBuffer.prototype.$conditionalHandlers = {
'$ne' : handleSingle
, '$in' : handleArray
, '$nin': handleArray
, '$gt' : handleSingle
, '$lt' : handleSingle
, '$gte': handleSingle
, '$lte': handleSingle
};
/**
* Casts contents for queries.
@ -148,7 +154,7 @@ SchemaBuffer.prototype.$conditionalHandlers = {
* @api private
*/
SchemaBuffer.prototype.castForQuery = function ($conditional, val) {
SchemaBuffer.prototype.castForQuery = function($conditional, val) {
var handler;
if (arguments.length === 2) {
handler = this.$conditionalHandlers[$conditional];

View File

@ -2,10 +2,13 @@
* Module requirements.
*/
var SchemaType = require('../schematype');
var CastError = SchemaType.CastError;
var errorMessages = require('../error').messages;
var utils = require('../utils');
var SchemaType = require('../schematype');
var CastError = SchemaType.CastError;
/**
* Date SchemaType constructor.
*
@ -15,15 +18,23 @@ var utils = require('../utils');
* @api private
*/
function SchemaDate (key, options) {
SchemaType.call(this, key, options);
};
function SchemaDate(key, options) {
SchemaType.call(this, key, options, 'Date');
}
/**
* This schema type's name, to defend against minifiers that mangle
* function names.
*
* @api private
*/
SchemaDate.schemaName = 'Date';
/*!
* Inherits from SchemaType.
*/
SchemaDate.prototype.__proto__ = SchemaType.prototype;
SchemaDate.prototype = Object.create( SchemaType.prototype );
SchemaDate.prototype.constructor = SchemaDate;
/**
* Declares a TTL index (rounded to the nearest second) for _Date_ types only.
@ -56,7 +67,7 @@ SchemaDate.prototype.__proto__ = SchemaType.prototype;
* @api public
*/
SchemaDate.prototype.expires = function (when) {
SchemaDate.prototype.expires = function(when) {
if (!this._index || 'Object' !== this._index.constructor.name) {
this._index = {};
}
@ -72,10 +83,122 @@ SchemaDate.prototype.expires = function (when) {
* @api private
*/
SchemaDate.prototype.checkRequired = function (value) {
SchemaDate.prototype.checkRequired = function(value) {
return value instanceof Date;
};
/**
* Sets a minimum date validator.
*
* ####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') })
* m.save(function (err) {
* console.error(err) // validator error
* m.d = Date('2014-12-08');
* m.save() // success
* })
*
* // 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') });
* s.validate(function (err) {
* console.log(String(err)) // ValidationError: The value of path `d` (1969-12-31) is before the limit (1970-01-01).
* })
*
* @param {Date} value minimum date
* @param {String} [message] optional custom error message
* @return {SchemaType} this
* @see Customized Error Messages #error_messages_MongooseError-messages
* @api public
*/
SchemaDate.prototype.min = function(value, message) {
if (this.minValidator) {
this.validators = this.validators.filter(function(v) {
return v.validator != this.minValidator;
}, this);
}
if (value) {
var msg = message || errorMessages.Date.min;
msg = msg.replace(/{MIN}/, (value === Date.now ? 'Date.now()' : this.cast(value).toString()));
var self = this;
this.validators.push({
validator: this.minValidator = function(val) {
var min = (value === Date.now ? value() : self.cast(value));
return val === null || val.valueOf() >= min.valueOf();
},
message: msg,
type: 'min',
min: value
});
}
return this;
};
/**
* Sets a maximum date validator.
*
* ####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') })
* m.save(function (err) {
* console.error(err) // validator error
* m.d = Date('2013-12-31');
* m.save() // success
* })
*
* // 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') });
* s.validate(function (err) {
* console.log(String(err)) // ValidationError: The value of path `d` (2014-12-08) exceeds the limit (2014-01-01).
* })
*
* @param {Date} maximum date
* @param {String} [message] optional custom error message
* @return {SchemaType} this
* @see Customized Error Messages #error_messages_MongooseError-messages
* @api public
*/
SchemaDate.prototype.max = function(value, message) {
if (this.maxValidator) {
this.validators = this.validators.filter(function(v) {
return v.validator != this.maxValidator;
}, this);
}
if (value) {
var msg = message || errorMessages.Date.max;
msg = msg.replace(/{MAX}/, (value === Date.now ? 'Date.now()' : this.cast(value).toString()));
var self = this;
this.validators.push({
validator: this.maxValidator = function(val) {
var max = (value === Date.now ? value() : self.cast(value));
return val === null || val.valueOf() <= max.valueOf();
},
message: msg,
type: 'max',
max: value
});
}
return this;
};
/**
* Casts to date
*
@ -83,8 +206,9 @@ SchemaDate.prototype.checkRequired = function (value) {
* @api private
*/
SchemaDate.prototype.cast = function (value) {
if (value === null || value === '')
SchemaDate.prototype.cast = function(value) {
// If null or undefined
if (value == null || value === '')
return null;
if (value instanceof Date)
@ -93,16 +217,19 @@ SchemaDate.prototype.cast = function (value) {
var date;
// support for timestamps
if (value instanceof Number || 'number' == typeof value
|| String(value) == Number(value))
date = new Date(Number(value));
if (typeof value !== 'undefined') {
if (value instanceof Number || 'number' == typeof value
|| String(value) == Number(value)) {
date = new Date(Number(value));
} else if (value.toString) {
// support for date strings
date = new Date(value.toString());
}
// support for date strings
else if (value.toString)
date = new Date(value.toString());
if (date.toString() != 'Invalid Date')
return date;
if (date.toString() != 'Invalid Date') {
return date;
}
}
throw new CastError('date', value, this.path);
};
@ -113,27 +240,17 @@ SchemaDate.prototype.cast = function (value) {
* @api private
*/
function handleSingle (val) {
function handleSingle(val) {
return this.cast(val);
}
function handleArray (val) {
var self = this;
return val.map( function (m) {
return self.cast(m);
SchemaDate.prototype.$conditionalHandlers =
utils.options(SchemaType.prototype.$conditionalHandlers, {
'$gt': handleSingle,
'$gte': handleSingle,
'$lt': handleSingle,
'$lte': handleSingle
});
}
SchemaDate.prototype.$conditionalHandlers = {
'$lt': handleSingle
, '$lte': handleSingle
, '$gt': handleSingle
, '$gte': handleSingle
, '$ne': handleSingle
, '$in': handleArray
, '$nin': handleArray
, '$all': handleArray
};
/**
@ -144,7 +261,7 @@ SchemaDate.prototype.$conditionalHandlers = {
* @api private
*/
SchemaDate.prototype.castForQuery = function ($conditional, val) {
SchemaDate.prototype.castForQuery = function($conditional, val) {
var handler;
if (2 !== arguments.length) {

View File

@ -1,13 +1,14 @@
/* eslint no-empty: 1 */
/*!
* Module dependencies.
*/
var SchemaType = require('../schematype')
, ArrayType = require('./array')
, MongooseDocumentArray = require('../types/documentarray')
, Subdocument = require('../types/embedded')
, Document = require('../document');
var ArrayType = require('./array');
var CastError = require('../error/cast');
var MongooseDocumentArray = require('../types/documentarray');
var SchemaType = require('../schematype');
var Subdocument = require('../types/embedded');
/**
* SubdocsArray SchemaType constructor
@ -19,24 +20,22 @@ var SchemaType = require('../schematype')
* @api private
*/
function DocumentArray (key, schema, options) {
function DocumentArray(key, schema, options) {
// compile an embedded document for this schema
function EmbeddedDocument () {
function EmbeddedDocument() {
Subdocument.apply(this, arguments);
}
EmbeddedDocument.prototype.__proto__ = Subdocument.prototype;
EmbeddedDocument.prototype = Object.create(Subdocument.prototype);
EmbeddedDocument.prototype.$__setSchema(schema);
EmbeddedDocument.schema = schema;
// apply methods
for (var i in schema.methods) {
for (var i in schema.methods)
EmbeddedDocument.prototype[i] = schema.methods[i];
}
// apply statics
for (var i in schema.statics)
for (i in schema.statics)
EmbeddedDocument[i] = schema.statics[i];
EmbeddedDocument.options = options;
@ -48,18 +47,26 @@ function DocumentArray (key, schema, options) {
var path = this.path;
var fn = this.defaultValue;
this.default(function(){
this.default(function() {
var arr = fn.call(this);
if (!Array.isArray(arr)) arr = [arr];
return new MongooseDocumentArray(arr, path, this);
});
};
}
/**
* This schema type's name, to defend against minifiers that mangle
* function names.
*
* @api private
*/
DocumentArray.schemaName = 'DocumentArray';
/*!
* Inherits from ArrayType.
*/
DocumentArray.prototype.__proto__ = ArrayType.prototype;
DocumentArray.prototype = Object.create( ArrayType.prototype );
DocumentArray.prototype.constructor = DocumentArray;
/**
* Performs local validations first, then validations on each embedded doc
@ -67,14 +74,14 @@ DocumentArray.prototype.__proto__ = ArrayType.prototype;
* @api private
*/
DocumentArray.prototype.doValidate = function (array, fn, scope) {
var self = this;
DocumentArray.prototype.doValidate = function(array, fn, scope) {
SchemaType.prototype.doValidate.call(this, array, function(err) {
if (err) {
return fn(err);
}
SchemaType.prototype.doValidate.call(this, array, function (err) {
if (err) return fn(err);
var count = array && array.length
, error;
var count = array && array.length;
var error;
if (!count) return fn();
@ -86,24 +93,61 @@ DocumentArray.prototype.doValidate = function (array, fn, scope) {
// sidestep sparse entries
var doc = array[i];
if (!doc) {
--count || fn();
--count || fn(error);
continue;
}
;(function (i) {
doc.validate(function (err) {
if (err && !error) {
// rewrite the key
err.key = self.key + '.' + i + '.' + err.key;
return fn(error = err);
}
--count || fn();
});
})(i);
doc.validate(function(err) {
if (err) {
error = err;
}
--count || fn(error);
});
}
}, scope);
};
/**
* Performs local validations first, then validations on each embedded doc.
*
* ####Note:
*
* This method ignores the asynchronous validators.
*
* @return {MongooseError|undefined}
* @api private
*/
DocumentArray.prototype.doValidateSync = function(array, scope) {
var schemaTypeError = SchemaType.prototype.doValidateSync.call(this, array, scope);
if (schemaTypeError) return schemaTypeError;
var count = array && array.length,
resultError = null;
if (!count) return;
// handle sparse arrays, do not use array.forEach which does not
// iterate over sparse elements yet reports array.length including
// them :(
for (var i = 0, len = count; i < len; ++i) {
// only first error
if ( resultError ) break;
// sidestep sparse entries
var doc = array[i];
if (!doc) continue;
var subdocValidateError = doc.validateSync();
if (subdocValidateError) {
resultError = subdocValidateError;
}
}
return resultError;
};
/**
* Casts contents
*
@ -112,17 +156,27 @@ DocumentArray.prototype.doValidate = function (array, fn, scope) {
* @api private
*/
DocumentArray.prototype.cast = function (value, doc, init, prev) {
var selected
, subdoc
, i
DocumentArray.prototype.cast = function(value, doc, init, prev) {
var selected,
subdoc,
i;
if (!Array.isArray(value)) {
// gh-2442 mark whole array as modified if we're initializing a doc from
// the db and the path isn't an array in the document
if (!!doc && init) {
doc.markModified(this.path);
}
return this.cast([value], doc, init, prev);
}
if (!(value instanceof MongooseDocumentArray)) {
if (!(value && value.isMongooseDocumentArray)) {
value = new MongooseDocumentArray(value, this.path, doc);
if (prev && prev._handlers) {
for (var key in prev._handlers) {
doc.removeListener(key, prev._handlers[key]);
}
}
}
i = value.length;
@ -131,26 +185,37 @@ DocumentArray.prototype.cast = function (value, doc, init, prev) {
if (!(value[i] instanceof Subdocument) && value[i]) {
if (init) {
selected || (selected = scopePaths(this, doc.$__.selected, init));
subdoc = new this.casterConstructor(null, value, true, selected);
subdoc = new this.casterConstructor(null, value, true, selected, i);
value[i] = subdoc.init(value[i]);
} else {
if (prev && (subdoc = prev.id(value[i]._id))) {
try {
subdoc = prev.id(value[i]._id);
} catch (e) {}
if (prev && subdoc) {
// handle resetting doc with existing id but differing data
// doc.array = [{ doc: 'val' }]
subdoc.set(value[i]);
// if set() is hooked it will have no return value
// see gh-746
value[i] = subdoc;
} else {
subdoc = new this.casterConstructor(value[i], value);
try {
subdoc = new this.casterConstructor(value[i], value, undefined,
undefined, i);
// if set() is hooked it will have no return value
// see gh-746
value[i] = subdoc;
} catch (error) {
throw new CastError('embedded', value[i], value._path);
}
}
// if set() is hooked it will have no return value
// see gh-746
value[i] = subdoc;
}
}
}
return value;
}
};
/*!
* Scopes paths selected in a query to this array.
@ -161,15 +226,15 @@ DocumentArray.prototype.cast = function (value, doc, init, prev) {
* @param {Boolean|undefined} init - if we are being created part of a query result
*/
function scopePaths (array, fields, init) {
function scopePaths(array, fields, init) {
if (!(init && fields)) return undefined;
var path = array.path + '.'
, keys = Object.keys(fields)
, i = keys.length
, selected = {}
, hasKeys
, key
var path = array.path + '.',
keys = Object.keys(fields),
i = keys.length,
selected = {},
hasKeys,
key;
while (i--) {
key = keys[i];

118
node_modules/mongoose/lib/schema/embedded.js generated vendored Normal file
View File

@ -0,0 +1,118 @@
var SchemaType = require('../schematype');
var Subdocument = require('../types/subdocument');
module.exports = Embedded;
/**
* Sub-schema schematype constructor
*
* @param {Schema} schema
* @param {String} key
* @param {Object} options
* @inherits SchemaType
* @api private
*/
function Embedded(schema, path, options) {
var _embedded = function() {
Subdocument.apply(this, arguments);
};
_embedded.prototype = Object.create(Subdocument.prototype);
_embedded.prototype.$__setSchema(schema);
_embedded.schema = schema;
_embedded.$isSingleNested = true;
_embedded.prototype.$basePath = path;
// apply methods
for (var i in schema.methods) {
_embedded.prototype[i] = schema.methods[i];
}
// apply statics
for (i in schema.statics) {
_embedded[i] = schema.statics[i];
}
this.caster = _embedded;
this.schema = schema;
this.$isSingleNested = true;
SchemaType.call(this, path, options, 'Embedded');
}
Embedded.prototype = Object.create(SchemaType.prototype);
/**
* Casts contents
*
* @param {Object} value
* @api private
*/
Embedded.prototype.cast = function(val, doc) {
var subdoc = new this.caster();
subdoc = subdoc.init(val);
subdoc.$parent = doc;
return subdoc;
};
/**
* Casts contents for query
*
* @param {string} [$conditional] optional query operator (like `$eq` or `$in`)
* @param {any} value
* @api private
*/
Embedded.prototype.castForQuery = function($conditional, val) {
var handler;
if (arguments.length === 2) {
handler = this.$conditionalHandlers[$conditional];
if (!handler) {
throw new Error('Can\'t use ' + $conditional);
}
return handler.call(this, val);
} else {
val = $conditional;
return new this.caster(val).
toObject({ virtuals: false });
}
};
/**
* Async validation on this single nested doc.
*
* @api private
*/
Embedded.prototype.doValidate = function(value, fn) {
SchemaType.prototype.doValidate.call(this, value, function(error) {
if (error) {
return fn(error);
}
value.validate(fn, { __noPromise: true });
});
};
/**
* Synchronously validate this single nested doc
*
* @api private
*/
Embedded.prototype.doValidateSync = function(value) {
var schemaTypeError = SchemaType.prototype.doValidateSync.call(this, value);
if (schemaTypeError) {
return schemaTypeError;
}
return value.validateSync();
};
/**
* Required validator for single nested docs
*
* @api private
*/
Embedded.prototype.checkRequired = function(value) {
return !!value && value.$isSingleNested;
};

View File

@ -11,6 +11,8 @@ exports.Boolean = require('./boolean');
exports.DocumentArray = require('./documentarray');
exports.Embedded = require('./embedded');
exports.Array = require('./array');
exports.Buffer = require('./buffer');

View File

@ -15,7 +15,7 @@ var utils = require('../utils');
* @api private
*/
function Mixed (path, options) {
function Mixed(path, options) {
if (options && options.default) {
var def = options.default;
if (Array.isArray(def) && 0 === def.length) {
@ -25,20 +25,28 @@ function Mixed (path, options) {
utils.isObject(def) &&
0 === Object.keys(def).length) {
// prevent odd "shared" objects between documents
options.default = function () {
return {}
}
options.default = function() {
return {};
};
}
}
SchemaType.call(this, path, options);
};
SchemaType.call(this, path, options, 'Mixed');
}
/**
* This schema type's name, to defend against minifiers that mangle
* function names.
*
* @api private
*/
Mixed.schemaName = 'Mixed';
/*!
* Inherits from SchemaType.
*/
Mixed.prototype.__proto__ = SchemaType.prototype;
Mixed.prototype = Object.create( SchemaType.prototype );
Mixed.prototype.constructor = Mixed;
/**
* Required validator
@ -46,8 +54,8 @@ Mixed.prototype.__proto__ = SchemaType.prototype;
* @api private
*/
Mixed.prototype.checkRequired = function (val) {
return true;
Mixed.prototype.checkRequired = function(val) {
return (val !== undefined) && (val !== null);
};
/**
@ -59,7 +67,7 @@ Mixed.prototype.checkRequired = function (val) {
* @api private
*/
Mixed.prototype.cast = function (val) {
Mixed.prototype.cast = function(val) {
return val;
};
@ -71,7 +79,7 @@ Mixed.prototype.cast = function (val) {
* @api private
*/
Mixed.prototype.castForQuery = function ($cond, val) {
Mixed.prototype.castForQuery = function($cond, val) {
if (arguments.length === 2) return val;
return $cond;
};

View File

@ -2,10 +2,11 @@
* Module requirements.
*/
var SchemaType = require('../schematype')
, CastError = SchemaType.CastError
, utils = require('../utils')
, Document
var SchemaType = require('../schematype'),
CastError = SchemaType.CastError,
errorMessages = require('../error').messages,
utils = require('../utils'),
Document;
/**
* Number SchemaType constructor.
@ -16,15 +17,23 @@ var SchemaType = require('../schematype')
* @api private
*/
function SchemaNumber (key, options) {
function SchemaNumber(key, options) {
SchemaType.call(this, key, options, 'Number');
};
}
/**
* This schema type's name, to defend against minifiers that mangle
* function names.
*
* @api private
*/
SchemaNumber.schemaName = 'Number';
/*!
* Inherits from SchemaType.
*/
SchemaNumber.prototype.__proto__ = SchemaType.prototype;
SchemaNumber.prototype = Object.create( SchemaType.prototype );
SchemaNumber.prototype.constructor = SchemaNumber;
/**
* Required validator for number
@ -32,7 +41,7 @@ SchemaNumber.prototype.__proto__ = SchemaType.prototype;
* @api private
*/
SchemaNumber.prototype.checkRequired = function checkRequired (value, doc) {
SchemaNumber.prototype.checkRequired = function checkRequired(value, doc) {
if (SchemaType._isRef(this, value, doc, true)) {
return null != value;
} else {
@ -54,22 +63,41 @@ SchemaNumber.prototype.checkRequired = function checkRequired (value, doc) {
* m.save() // success
* })
*
* // 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 });
* s.validate(function (err) {
* console.log(String(err)) // ValidationError: The value of path `n` (4) is beneath the limit (10).
* })
*
* @param {Number} value minimum number
* @param {String} [message] optional custom error message
* @return {SchemaType} this
* @see Customized Error Messages #error_messages_MongooseError-messages
* @api public
*/
SchemaNumber.prototype.min = function (value) {
SchemaNumber.prototype.min = function(value, message) {
if (this.minValidator) {
this.validators = this.validators.filter(function (v) {
return 'min' != v[1];
});
this.validators = this.validators.filter(function(v) {
return v.validator != this.minValidator;
}, this);
}
if (value != null) {
this.validators.push([this.minValidator = function (v) {
return v === null || v >= value;
}, 'min']);
if (null != value) {
var msg = message || errorMessages.Number.min;
msg = msg.replace(/{MIN}/, value);
this.validators.push({
validator: this.minValidator = function(v) {
return v == null || v >= value;
},
message: msg,
type: 'min',
min: value
});
}
return this;
@ -89,22 +117,41 @@ SchemaNumber.prototype.min = function (value) {
* m.save() // success
* })
*
* // 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 });
* s.validate(function (err) {
* console.log(String(err)) // ValidationError: The value of path `n` (4) exceeds the limit (10).
* })
*
* @param {Number} maximum number
* @param {String} [message] optional custom error message
* @return {SchemaType} this
* @see Customized Error Messages #error_messages_MongooseError-messages
* @api public
*/
SchemaNumber.prototype.max = function (value) {
SchemaNumber.prototype.max = function(value, message) {
if (this.maxValidator) {
this.validators = this.validators.filter(function(v){
return 'max' != v[1];
});
this.validators = this.validators.filter(function(v) {
return v.validator != this.maxValidator;
}, this);
}
if (value != null) {
this.validators.push([this.maxValidator = function(v){
return v === null || v <= value;
}, 'max']);
if (null != value) {
var msg = message || errorMessages.Number.max;
msg = msg.replace(/{MAX}/, value);
this.validators.push({
validator: this.maxValidator = function(v) {
return v == null || v <= value;
},
message: msg,
type: 'max',
max: value
});
}
return this;
@ -119,7 +166,7 @@ SchemaNumber.prototype.max = function (value) {
* @api private
*/
SchemaNumber.prototype.cast = function (value, doc, init) {
SchemaNumber.prototype.cast = function(value, doc, init) {
if (SchemaType._isRef(this, value, doc, init)) {
// wait! we may need to cast this to a document
@ -157,15 +204,17 @@ SchemaNumber.prototype.cast = function (value, doc, init) {
? value._id // documents
: value;
if (!isNaN(val)){
if (!isNaN(val)) {
if (null === val) return val;
if ('' === val) return null;
if ('string' == typeof val) val = Number(val);
if (val instanceof Number) return val
if (typeof val === 'string' || typeof val === 'boolean') {
val = Number(val);
}
if (val instanceof Number) return val;
if ('number' == typeof val) return val;
if (val.toString && !Array.isArray(val) &&
val.toString() == Number(val)) {
return new Number(val)
return new Number(val);
}
}
@ -176,28 +225,28 @@ SchemaNumber.prototype.cast = function (value, doc, init) {
* ignore
*/
function handleSingle (val) {
return this.cast(val)
function handleSingle(val) {
return this.cast(val);
}
function handleArray (val) {
function handleArray(val) {
var self = this;
return val.map(function (m) {
return self.cast(m)
if (!Array.isArray(val)) {
return [this.cast(val)];
}
return val.map(function(m) {
return self.cast(m);
});
}
SchemaNumber.prototype.$conditionalHandlers = {
'$lt' : handleSingle
, '$lte': handleSingle
, '$gt' : handleSingle
, '$gte': handleSingle
, '$ne' : handleSingle
, '$in' : handleArray
, '$nin': handleArray
, '$mod': handleArray
, '$all': handleArray
};
SchemaNumber.prototype.$conditionalHandlers =
utils.options(SchemaType.prototype.$conditionalHandlers, {
'$gt' : handleSingle,
'$gte': handleSingle,
'$lt' : handleSingle,
'$lte': handleSingle,
'$mod': handleArray
});
/**
* Casts contents for queries.
@ -207,7 +256,7 @@ SchemaNumber.prototype.$conditionalHandlers = {
* @api private
*/
SchemaNumber.prototype.castForQuery = function ($conditional, val) {
SchemaNumber.prototype.castForQuery = function($conditional, val) {
var handler;
if (arguments.length === 2) {
handler = this.$conditionalHandlers[$conditional];
@ -216,7 +265,7 @@ SchemaNumber.prototype.castForQuery = function ($conditional, val) {
return handler.call(this, val);
} else {
val = this.cast($conditional);
return val == null ? val : val
return val == null ? val : val;
}
};

View File

@ -1,13 +1,14 @@
/* eslint no-empty: 1 */
/*!
* Module dependencies.
*/
var SchemaType = require('../schematype')
, CastError = SchemaType.CastError
, driver = global.MONGOOSE_DRIVER_PATH || './../drivers/node-mongodb-native'
, oid = require('../types/objectid')
, utils = require('../utils')
, Document
var SchemaType = require('../schematype'),
CastError = SchemaType.CastError,
oid = require('../types/objectid'),
utils = require('../utils'),
Document;
/**
* ObjectId SchemaType constructor.
@ -18,15 +19,23 @@ var SchemaType = require('../schematype')
* @api private
*/
function ObjectId (key, options) {
function ObjectId(key, options) {
SchemaType.call(this, key, options, 'ObjectID');
};
}
/**
* This schema type's name, to defend against minifiers that mangle
* function names.
*
* @api private
*/
ObjectId.schemaName = 'ObjectId';
/*!
* Inherits from SchemaType.
*/
ObjectId.prototype.__proto__ = SchemaType.prototype;
ObjectId.prototype = Object.create( SchemaType.prototype );
ObjectId.prototype.constructor = ObjectId;
/**
* Adds an auto-generated ObjectId default if turnOn is true.
@ -35,10 +44,10 @@ ObjectId.prototype.__proto__ = SchemaType.prototype;
* @return {SchemaType} this
*/
ObjectId.prototype.auto = function (turnOn) {
ObjectId.prototype.auto = function(turnOn) {
if (turnOn) {
this.default(defaultId);
this.set(resetId)
this.set(resetId);
}
return this;
@ -50,7 +59,7 @@ ObjectId.prototype.auto = function (turnOn) {
* @api private
*/
ObjectId.prototype.checkRequired = function checkRequired (value, doc) {
ObjectId.prototype.checkRequired = function checkRequired(value, doc) {
if (SchemaType._isRef(this, value, doc, true)) {
return null != value;
} else {
@ -67,7 +76,7 @@ ObjectId.prototype.checkRequired = function checkRequired (value, doc) {
* @api private
*/
ObjectId.prototype.cast = function (value, doc, init) {
ObjectId.prototype.cast = function(value, doc, init) {
if (SchemaType._isRef(this, value, doc, init)) {
// wait! we may need to cast this to a document
@ -101,17 +110,26 @@ ObjectId.prototype.cast = function (value, doc, init) {
return ret;
}
if (value === null) return value;
// If null or undefined
if (value == null) return value;
if (value instanceof oid)
return value;
if (value._id && value._id instanceof oid)
return value._id;
if (value._id) {
if (value._id instanceof oid) {
return value._id;
}
if (value._id.toString instanceof Function) {
try {
return oid.createFromHexString(value._id.toString());
} catch (e) {}
}
}
if (value.toString) {
if (value.toString instanceof Function) {
try {
return oid.fromString(value.toString());
return oid.createFromHexString(value.toString());
} catch (err) {
throw new CastError('ObjectId', value, this.path);
}
@ -124,27 +142,17 @@ ObjectId.prototype.cast = function (value, doc, init) {
* ignore
*/
function handleSingle (val) {
function handleSingle(val) {
return this.cast(val);
}
function handleArray (val) {
var self = this;
return val.map(function (m) {
return self.cast(m);
ObjectId.prototype.$conditionalHandlers =
utils.options(SchemaType.prototype.$conditionalHandlers, {
'$gt': handleSingle,
'$gte': handleSingle,
'$lt': handleSingle,
'$lte': handleSingle
});
}
ObjectId.prototype.$conditionalHandlers = {
'$ne': handleSingle
, '$in': handleArray
, '$nin': handleArray
, '$gt': handleSingle
, '$lt': handleSingle
, '$gte': handleSingle
, '$lte': handleSingle
, '$all': handleArray
};
/**
* Casts contents for queries.
@ -154,7 +162,7 @@ ObjectId.prototype.$conditionalHandlers = {
* @api private
*/
ObjectId.prototype.castForQuery = function ($conditional, val) {
ObjectId.prototype.castForQuery = function($conditional, val) {
var handler;
if (arguments.length === 2) {
handler = this.$conditionalHandlers[$conditional];
@ -170,11 +178,11 @@ ObjectId.prototype.castForQuery = function ($conditional, val) {
* ignore
*/
function defaultId () {
function defaultId() {
return new oid();
};
}
function resetId (v) {
function resetId(v) {
this.$__._id = null;
return v;
}

View File

@ -3,10 +3,11 @@
* Module dependencies.
*/
var SchemaType = require('../schematype')
, CastError = SchemaType.CastError
, utils = require('../utils')
, Document
var SchemaType = require('../schematype'),
CastError = SchemaType.CastError,
errorMessages = require('../error').messages,
utils = require('../utils'),
Document;
/**
* String SchemaType constructor.
@ -17,64 +18,100 @@ var SchemaType = require('../schematype')
* @api private
*/
function SchemaString (key, options) {
function SchemaString(key, options) {
this.enumValues = [];
this.regExp = null;
SchemaType.call(this, key, options, 'String');
};
}
/**
* This schema type's name, to defend against minifiers that mangle
* function names.
*
* @api private
*/
SchemaString.schemaName = 'String';
/*!
* Inherits from SchemaType.
*/
SchemaString.prototype.__proto__ = SchemaType.prototype;
SchemaString.prototype = Object.create( SchemaType.prototype );
SchemaString.prototype.constructor = SchemaString;
/**
* Adds enumeration values and a coinciding validator.
* Adds an enum validator
*
* ####Example:
*
* var states = 'opening open closing closed'.split(' ')
* var s = new Schema({ state: { type: String, enum: states })
* var s = new Schema({ state: { type: String, enum: states }})
* var M = db.model('M', s)
* var m = new M({ state: 'invalid' })
* m.save(function (err) {
* console.error(err) // validator error
* console.error(String(err)) // ValidationError: `invalid` is not a valid enum value for path `state`.
* m.state = 'open'
* m.save() // success
* m.save(callback) // success
* })
*
* @param {String} [args...] enumeration values
* // or with custom error messages
* var enu = {
* values: 'opening open closing closed'.split(' '),
* message: 'enum validator failed for path `{PATH}` with value `{VALUE}`'
* }
* var s = new Schema({ state: { type: String, enum: enu })
* var M = db.model('M', s)
* var 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'
* m.save(callback) // success
* })
*
* @param {String|Object} [args...] enumeration values
* @return {SchemaType} this
* @see Customized Error Messages #error_messages_MongooseError-messages
* @api public
*/
SchemaString.prototype.enum = function () {
var len = arguments.length;
SchemaString.prototype.enum = function() {
if (this.enumValidator) {
this.validators = this.validators.filter(function(v) {
return v.validator != this.enumValidator;
}, this);
this.enumValidator = false;
}
if (!len || undefined === arguments[0] || false === arguments[0]) {
if (this.enumValidator){
this.enumValidator = false;
this.validators = this.validators.filter(function(v){
return v[1] != 'enum';
});
}
if (undefined === arguments[0] || false === arguments[0]) {
return this;
}
for (var i = 0; i < len; i++) {
if (undefined !== arguments[i]) {
this.enumValues.push(this.cast(arguments[i]));
var values;
var errorMessage;
if (utils.isObject(arguments[0])) {
values = arguments[0].values;
errorMessage = arguments[0].message;
} else {
values = arguments;
errorMessage = errorMessages.String.enum;
}
for (var i = 0; i < values.length; i++) {
if (undefined !== values[i]) {
this.enumValues.push(this.cast(values[i]));
}
}
if (!this.enumValidator) {
var values = this.enumValues;
this.enumValidator = function(v){
return undefined === v || ~values.indexOf(v);
};
this.validators.push([this.enumValidator, 'enum']);
}
var vals = this.enumValues;
this.enumValidator = function(v) {
return undefined === v || ~vals.indexOf(v);
};
this.validators.push({
validator: this.enumValidator,
message: errorMessage,
type: 'enum',
enumValues: vals
});
return this;
};
@ -93,9 +130,9 @@ SchemaString.prototype.enum = function () {
* @return {SchemaType} this
*/
SchemaString.prototype.lowercase = function () {
return this.set(function (v, self) {
if ('string' != typeof v) v = self.cast(v)
SchemaString.prototype.lowercase = function() {
return this.set(function(v, self) {
if ('string' != typeof v) v = self.cast(v);
if (v) return v.toLowerCase();
return v;
});
@ -115,9 +152,9 @@ SchemaString.prototype.lowercase = function () {
* @return {SchemaType} this
*/
SchemaString.prototype.uppercase = function () {
return this.set(function (v, self) {
if ('string' != typeof v) v = self.cast(v)
SchemaString.prototype.uppercase = function() {
return this.set(function(v, self) {
if ('string' != typeof v) v = self.cast(v);
if (v) return v.toUpperCase();
return v;
});
@ -141,14 +178,122 @@ SchemaString.prototype.uppercase = function () {
* @return {SchemaType} this
*/
SchemaString.prototype.trim = function () {
return this.set(function (v, self) {
if ('string' != typeof v) v = self.cast(v)
SchemaString.prototype.trim = function() {
return this.set(function(v, self) {
if ('string' != typeof v) v = self.cast(v);
if (v) return v.trim();
return v;
});
};
/**
* Sets a minimum length validator.
*
* ####Example:
*
* var schema = new Schema({ postalCode: { type: String, minlength: 5 })
* var Address = db.model('Address', schema)
* var address = new Address({ postalCode: '9512' })
* address.save(function (err) {
* console.error(err) // validator error
* address.postalCode = '95125';
* address.save() // success
* })
*
* // 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' });
* address.validate(function (err) {
* console.log(String(err)) // ValidationError: The value of path `postalCode` (`9512`) is shorter than the minimum length (5).
* })
*
* @param {Number} value minimum string length
* @param {String} [message] optional custom error message
* @return {SchemaType} this
* @see Customized Error Messages #error_messages_MongooseError-messages
* @api public
*/
SchemaString.prototype.minlength = function(value, message) {
if (this.minlengthValidator) {
this.validators = this.validators.filter(function(v) {
return v.validator != this.minlengthValidator;
}, this);
}
if (null != value) {
var msg = message || errorMessages.String.minlength;
msg = msg.replace(/{MINLENGTH}/, value);
this.validators.push({
validator: this.minlengthValidator = function(v) {
return v === null || v.length >= value;
},
message: msg,
type: 'minlength',
minlength: value
});
}
return this;
};
/**
* 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' })
* address.save(function (err) {
* console.error(err) // validator error
* address.postalCode = '95125';
* address.save() // success
* })
*
* // 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' });
* address.validate(function (err) {
* console.log(String(err)) // ValidationError: The value of path `postalCode` (`9512512345`) exceeds the maximum allowed length (9).
* })
*
* @param {Number} value maximum string length
* @param {String} [message] optional custom error message
* @return {SchemaType} this
* @see Customized Error Messages #error_messages_MongooseError-messages
* @api public
*/
SchemaString.prototype.maxlength = function(value, message) {
if (this.maxlengthValidator) {
this.validators = this.validators.filter(function(v) {
return v.validator != this.maxlengthValidator;
}, this);
}
if (null != value) {
var msg = message || errorMessages.String.maxlength;
msg = msg.replace(/{MAXLENGTH}/, value);
this.validators.push({
validator: this.maxlengthValidator = function(v) {
return v === null || v.length <= value;
},
message: msg,
type: 'maxlength',
maxlength: value
});
}
return this;
};
/**
* Sets a regexp validator.
*
@ -158,27 +303,57 @@ SchemaString.prototype.trim = function () {
*
* var s = new Schema({ name: { type: String, match: /^a/ }})
* var M = db.model('M', s)
* var m = new M({ name: 'invalid' })
* var m = new M({ name: 'I am invalid' })
* m.validate(function (err) {
* console.error(err) // validation error
* console.error(String(err)) // "ValidationError: Path `name` is invalid (I am invalid)."
* m.name = 'apples'
* m.validate(function (err) {
* assert.ok(err) // success
* })
* })
*
* // 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' });
* 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 }})
*
* @param {RegExp} regExp regular expression to test against
* @param {String} [message] optional custom error message
* @return {SchemaType} this
* @see Customized Error Messages #error_messages_MongooseError-messages
* @api public
*/
SchemaString.prototype.match = function match (regExp) {
this.validators.push([function(v){
return null != v && '' !== v
? regExp.test(v)
: true
}, 'regexp']);
SchemaString.prototype.match = function match(regExp, message) {
// yes, we allow multiple match validators
var msg = message || errorMessages.String.match;
var matchValidator = function(v) {
if (!regExp) {
return false;
}
var ret = ((null != v && '' !== v)
? regExp.test(v)
: true);
return ret;
};
this.validators.push({
validator: matchValidator,
message: msg,
type: 'regexp',
regexp: regExp
});
return this;
};
@ -189,7 +364,7 @@ SchemaString.prototype.match = function match (regExp) {
* @api private
*/
SchemaString.prototype.checkRequired = function checkRequired (value, doc) {
SchemaString.prototype.checkRequired = function checkRequired(value, doc) {
if (SchemaType._isRef(this, value, doc, true)) {
return null != value;
} else {
@ -203,7 +378,7 @@ SchemaString.prototype.checkRequired = function checkRequired (value, doc) {
* @api private
*/
SchemaString.prototype.cast = function (value, doc, init) {
SchemaString.prototype.cast = function(value, doc, init) {
if (SchemaType._isRef(this, value, doc, init)) {
// wait! we may need to cast this to a document
@ -237,7 +412,8 @@ SchemaString.prototype.cast = function (value, doc, init) {
return ret;
}
if (value === null) {
// If null or undefined
if (value == null) {
return value;
}
@ -246,12 +422,15 @@ SchemaString.prototype.cast = function (value, doc, init) {
if (value._id && 'string' == typeof value._id) {
return value._id;
}
if (value.toString) {
// Re: gh-647 and gh-3030, we're ok with casting using `toString()`
// **unless** its the default Object.toString, because "[object Object]"
// doesn't really qualify as useful data
if (value.toString && value.toString !== Object.prototype.toString) {
return value.toString();
}
}
throw new CastError('string', value, this.path);
};
@ -259,29 +438,30 @@ SchemaString.prototype.cast = function (value, doc, init) {
* ignore
*/
function handleSingle (val) {
function handleSingle(val) {
return this.castForQuery(val);
}
function handleArray (val) {
function handleArray(val) {
var self = this;
return val.map(function (m) {
if (!Array.isArray(val)) {
return [this.castForQuery(val)];
}
return val.map(function(m) {
return self.castForQuery(m);
});
}
SchemaString.prototype.$conditionalHandlers = {
'$ne' : handleSingle
, '$in' : handleArray
, '$nin': handleArray
, '$gt' : handleSingle
, '$lt' : handleSingle
, '$gte': handleSingle
, '$lte': handleSingle
, '$all': handleArray
, '$regex': handleSingle
, '$options': handleSingle
};
SchemaString.prototype.$conditionalHandlers =
utils.options(SchemaType.prototype.$conditionalHandlers, {
'$all': handleArray,
'$gt' : handleSingle,
'$gte': handleSingle,
'$lt' : handleSingle,
'$lte': handleSingle,
'$options': handleSingle,
'$regex': handleSingle
});
/**
* Casts contents for queries.
@ -291,7 +471,7 @@ SchemaString.prototype.$conditionalHandlers = {
* @api private
*/
SchemaString.prototype.castForQuery = function ($conditional, val) {
SchemaString.prototype.castForQuery = function($conditional, val) {
var handler;
if (arguments.length === 2) {
handler = this.$conditionalHandlers[$conditional];