1
0
mirror of https://github.com/mgerb/mywebsite synced 2026-01-13 11:12:47 +00:00

Added all files

This commit is contained in:
2015-06-24 11:18:57 -05:00
parent 4c1ff3628c
commit a2c44e494f
2633 changed files with 459257 additions and 0 deletions

488
node_modules/mongoose/lib/aggregate.js generated vendored Normal file
View File

@@ -0,0 +1,488 @@
/*!
* Module dependencies
*/
var Promise = require('./promise')
, util = require('util')
, utils = require('./utils')
, Query = require('./query')
, read = Query.prototype.read
/**
* Aggregate constructor used for building aggregation pipelines.
*
* ####Example:
*
* new Aggregate();
* new Aggregate({ $project: { a: 1, b: 1 } });
* new Aggregate({ $project: { a: 1, b: 1 } }, { $skip: 5 });
* new Aggregate([{ $project: { a: 1, b: 1 } }, { $skip: 5 }]);
*
* Returned when calling Model.aggregate().
*
* ####Example:
*
* Model
* .aggregate({ $match: { age: { $gte: 21 }}})
* .unwind('tags')
* .exec(callback)
*
* ####Note:
*
* - The documents returned are plain javascript objects, not mongoose documents (since any shape of document can be returned).
* - Requires MongoDB >= 2.1
*
* @see MongoDB http://docs.mongodb.org/manual/applications/aggregation/
* @see driver http://mongodb.github.com/node-mongodb-native/api-generated/collection.html#aggregate
* @param {Object|Array} [ops] aggregation operator(s) or operator array
* @api public
*/
function Aggregate () {
this._pipeline = [];
this._model = undefined;
this.options = undefined;
if (1 === arguments.length && util.isArray(arguments[0])) {
this.append.apply(this, arguments[0]);
} else {
this.append.apply(this, arguments);
}
}
/**
* Binds this aggregate to a model.
*
* @param {Model} model the model to which the aggregate is to be bound
* @return {Aggregate}
* @api private
*/
Aggregate.prototype.bind = function (model) {
this._model = model;
return this;
}
/**
* Appends new operators to this aggregate pipeline
*
* ####Examples:
*
* aggregate.append({ $project: { field: 1 }}, { $limit: 2 });
*
* // or pass an array
* var pipeline = [{ $match: { daw: 'Logic Audio X' }} ];
* aggregate.append(pipeline);
*
* @param {Object} ops operator(s) to append
* @return {Aggregate}
* @api public
*/
Aggregate.prototype.append = function () {
var args = utils.args(arguments)
, arg;
if (!args.every(isOperator)) {
throw new Error("Arguments must be aggregate pipeline operators");
}
this._pipeline = this._pipeline.concat(args);
return this;
}
/**
* Appends a new $project operator to this aggregate pipeline.
*
* Mongoose query [selection syntax](#query_Query-select) is also supported.
*
* ####Examples:
*
* // include a, include b, exclude _id
* aggregate.project("a b -_id");
*
* // or you may use object notation, useful when
* // you have keys already prefixed with a "-"
* aggregate.project({a: 1, b: 1, _id: 0});
*
* // reshaping documents
* aggregate.project({
* newField: '$b.nested'
* , plusTen: { $add: ['$val', 10]}
* , sub: {
* name: '$a'
* }
* })
*
* // etc
* aggregate.project({ salary_k: { $divide: [ "$salary", 1000 ] } });
*
* @param {Object|String} arg field specification
* @see projection http://docs.mongodb.org/manual/reference/aggregation/project/
* @return {Aggregate}
* @api public
*/
Aggregate.prototype.project = function (arg) {
var fields = {};
if ('object' === typeof arg && !util.isArray(arg)) {
Object.keys(arg).forEach(function (field) {
fields[field] = arg[field];
});
} else if (1 === arguments.length && 'string' === typeof arg) {
arg.split(/\s+/).forEach(function (field) {
if (!field) return;
var include = '-' == field[0] ? 0 : 1;
if (include === 0) field = field.substring(1);
fields[field] = include;
});
} else {
throw new Error("Invalid project() argument. Must be string or object");
}
return this.append({ $project: fields });
}
/**
* Appends a new custom $group operator to this aggregate pipeline.
*
* ####Examples:
*
* aggregate.group({ _id: "$department" });
*
* @see $group http://docs.mongodb.org/manual/reference/aggregation/group/
* @method group
* @memberOf Aggregate
* @param {Object} arg $group operator contents
* @return {Aggregate}
* @api public
*/
/**
* Appends a new custom $match operator to this aggregate pipeline.
*
* ####Examples:
*
* aggregate.match({ department: { $in: [ "sales", "engineering" } } });
*
* @see $match http://docs.mongodb.org/manual/reference/aggregation/match/
* @method match
* @memberOf Aggregate
* @param {Object} arg $match operator contents
* @return {Aggregate}
* @api public
*/
/**
* Appends a new $skip operator to this aggregate pipeline.
*
* ####Examples:
*
* aggregate.skip(10);
*
* @see $skip http://docs.mongodb.org/manual/reference/aggregation/skip/
* @method skip
* @memberOf Aggregate
* @param {Number} num number of records to skip before next stage
* @return {Aggregate}
* @api public
*/
/**
* Appends a new $limit operator to this aggregate pipeline.
*
* ####Examples:
*
* aggregate.limit(10);
*
* @see $limit http://docs.mongodb.org/manual/reference/aggregation/limit/
* @method limit
* @memberOf Aggregate
* @param {Number} num maximum number of records to pass to the next stage
* @return {Aggregate}
* @api public
*/
/**
* Appends a new $geoNear operator to this aggregate pipeline.
*
* ####NOTE:
*
* **MUST** be used as the first operator in the pipeline.
*
* ####Examples:
*
* aggregate.near({
* near: [40.724, -73.997],
* distanceField: "dist.calculated", // required
* maxDistance: 0.008,
* query: { type: "public" },
* includeLocs: "dist.location",
* uniqueDocs: true,
* num: 5
* });
*
* @see $geoNear http://docs.mongodb.org/manual/reference/aggregation/geoNear/
* @method near
* @memberOf Aggregate
* @param {Object} parameters
* @return {Aggregate}
* @api public
*/
Aggregate.prototype.near = function (arg) {
var op = {};
op.$geoNear = arg;
return this.append(op);
};
/*!
* define methods
*/
'group match skip limit out'.split(' ').forEach(function ($operator) {
Aggregate.prototype[$operator] = function (arg) {
var op = {};
op['$' + $operator] = arg;
return this.append(op);
};
});
/**
* Appends new custom $unwind operator(s) to this aggregate pipeline.
*
* ####Examples:
*
* aggregate.unwind("tags");
* aggregate.unwind("a", "b", "c");
*
* @see $unwind http://docs.mongodb.org/manual/reference/aggregation/unwind/
* @param {String} fields the field(s) to unwind
* @return {Aggregate}
* @api public
*/
Aggregate.prototype.unwind = function () {
var args = utils.args(arguments);
return this.append.apply(this, args.map(function (arg) {
return { $unwind: '$' + arg };
}));
}
/**
* Appends a new $sort operator to this aggregate pipeline.
*
* If an object is passed, values allowed are `asc`, `desc`, `ascending`, `descending`, `1`, and `-1`.
*
* If a string is passed, it must be a space delimited list of path names. The sort order of each path is ascending unless the path name is prefixed with `-` which will be treated as descending.
*
* ####Examples:
*
* // these are equivalent
* aggregate.sort({ field: 'asc', test: -1 });
* aggregate.sort('field -test');
*
* @see $sort http://docs.mongodb.org/manual/reference/aggregation/sort/
* @param {Object|String} arg
* @return {Aggregate} this
* @api public
*/
Aggregate.prototype.sort = function (arg) {
// TODO refactor to reuse the query builder logic
var sort = {};
if ('Object' === arg.constructor.name) {
var desc = ['desc', 'descending', -1];
Object.keys(arg).forEach(function (field) {
sort[field] = desc.indexOf(arg[field]) === -1 ? 1 : -1;
});
} else if (1 === arguments.length && 'string' == typeof arg) {
arg.split(/\s+/).forEach(function (field) {
if (!field) return;
var ascend = '-' == field[0] ? -1 : 1;
if (ascend === -1) field = field.substring(1);
sort[field] = ascend;
});
} else {
throw new TypeError('Invalid sort() argument. Must be a string or object.');
}
return this.append({ $sort: sort });
}
/**
* Sets the readPreference option for the aggregation query.
*
* ####Example:
*
* Model.aggregate(..).read('primaryPreferred').exec(callback)
*
* @param {String} pref one of the listed preference options or their aliases
* @param {Array} [tags] optional tags for this query
* @see mongodb http://docs.mongodb.org/manual/applications/replication/#read-preference
* @see driver http://mongodb.github.com/node-mongodb-native/driver-articles/anintroductionto1_1and2_2.html#read-preferences
*/
Aggregate.prototype.read = function (pref) {
if (!this.options) this.options = {};
read.apply(this, arguments);
return this;
};
/**
* Sets the allowDiskUse option for the aggregation query (ignored for < 2.6.0)
*
* ####Example:
*
* Model.aggregate(..).allowDiskUse(true).exec(callback)
*
* @param {Boolean} value Should tell server it can use hard drive to store data during aggregation.
* @param {Array} [tags] optional tags for this query
* @see mongodb http://docs.mongodb.org/manual/reference/command/aggregate/
*/
Aggregate.prototype.allowDiskUse = function(value) {
if (!this.options) this.options = {};
this.options.allowDiskUse = value;
return this;
};
/**
* Sets the cursor option option for the aggregation query (ignored for < 2.6.0).
* Note the different syntax below: .exec() returns a cursor object, and no callback
* is necessary.
*
* ####Example:
*
* var cursor = Model.aggregate(..).cursor({ batchSize: 1000 }).exec();
* cursor.each(function(error, doc) {
* // use doc
* });
*
* @param {Object} options set the cursor batch size
* @see mongodb http://mongodb.github.io/node-mongodb-native/2.0/api/AggregationCursor.html
*/
Aggregate.prototype.cursor = function(options) {
if (!this.options) this.options = {};
this.options.cursor = options;
return this;
};
/**
* Executes the aggregate pipeline on the currently bound Model.
*
* ####Example:
*
* aggregate.exec(callback);
*
* // Because a promise is returned, the `callback` is optional.
* var promise = aggregate.exec();
* promise.then(..);
*
* @see Promise #promise_Promise
* @param {Function} [callback]
* @return {Promise}
* @api public
*/
Aggregate.prototype.exec = function (callback) {
var promise = new Promise();
if (callback) {
promise.addBack(callback);
}
if (!this._pipeline.length) {
promise.error(new Error("Aggregate has empty pipeline"));
return promise;
}
if (!this._model) {
promise.error(new Error("Aggregate not bound to any Model"));
return promise;
}
prepareDiscriminatorPipeline(this);
if (this.options && this.options.cursor) {
return this._model.collection.aggregate(this._pipeline, this.options || {});
}
this._model
.collection
.aggregate(this._pipeline, this.options || {}, promise.resolve.bind(promise));
return promise;
};
/*!
* Helpers
*/
/**
* Checks whether an object is likely a pipeline operator
*
* @param {Object} obj object to check
* @return {Boolean}
* @api private
*/
function isOperator (obj) {
var k;
if ('object' !== typeof obj) {
return false;
}
k = Object.keys(obj);
return 1 === k.length && k.some(function (key) {
return '$' === key[0];
});
}
/*!
* Adds the appropriate `$match` pipeline step to the top of an aggregate's
* pipeline, should it's model is a non-root discriminator type. This is
* analogous to the `prepareDiscriminatorCriteria` function in `lib/query.js`.
*
* @param {Aggregate} aggregate Aggregate to prepare
*/
function prepareDiscriminatorPipeline (aggregate) {
var schema = aggregate._model.schema,
discriminatorMapping = schema && schema.discriminatorMapping;
if (discriminatorMapping && !discriminatorMapping.isRoot) {
var originalPipeline = aggregate._pipeline,
discriminatorKey = discriminatorMapping.key,
discriminatorValue = discriminatorMapping.value;
// If the first pipeline stage is a match and it doesn't specify a `__t`
// key, add the discriminator key to it. This allows for potential
// aggregation query optimizations not to be disturbed by this feature.
if (originalPipeline[0] && originalPipeline[0].$match &&
!originalPipeline[0].$match[discriminatorKey]) {
originalPipeline[0].$match[discriminatorKey] = discriminatorValue;
// `originalPipeline` is a ref, so there's no need for
// aggregate._pipeline = originalPipeline
} else {
var match = {};
match[discriminatorKey] = discriminatorValue;
aggregate._pipeline = [{ $match: match }].concat(originalPipeline);
}
}
}
/*!
* Exports
*/
module.exports = Aggregate;

97
node_modules/mongoose/lib/browser.js generated vendored Normal file
View File

@@ -0,0 +1,97 @@
/**
* The [MongooseError](#error_MongooseError) constructor.
*
* @method Error
* @api public
*/
exports.Error = require('./error');
/**
* The Mongoose [Schema](#schema_Schema) constructor
*
* ####Example:
*
* var mongoose = require('mongoose');
* var Schema = mongoose.Schema;
* var CatSchema = new Schema(..);
*
* @method Schema
* @api public
*/
exports.Schema = require('./schema');
/**
* The various Mongoose Types.
*
* ####Example:
*
* var mongoose = require('mongoose');
* var array = mongoose.Types.Array;
*
* ####Types:
*
* - [ObjectId](#types-objectid-js)
* - [Buffer](#types-buffer-js)
* - [SubDocument](#types-embedded-js)
* - [Array](#types-array-js)
* - [DocumentArray](#types-documentarray-js)
*
* Using this exposed access to the `ObjectId` type, we can construct ids on demand.
*
* var ObjectId = mongoose.Types.ObjectId;
* var id1 = new ObjectId;
*
* @property Types
* @api public
*/
exports.Types = require('./types');
/**
* The Mongoose [VirtualType](#virtualtype_VirtualType) constructor
*
* @method VirtualType
* @api public
*/
exports.VirtualType = require('./virtualtype');
/**
* The various Mongoose SchemaTypes.
*
* ####Note:
*
* _Alias of mongoose.Schema.Types for backwards compatibility._
*
* @property SchemaTypes
* @see Schema.SchemaTypes #schema_Schema.Types
* @api public
*/
exports.SchemaType = require('./schematype.js');
/**
* Internal utils
*
* @property utils
* @api private
*/
exports.utils = require('./utils.js');
/**
* The Mongoose browser [Document](#document-js) constructor.
*
* @method Document
* @api public
*/
exports.Document = require('./document_provider.js')();
/*!
* Module exports.
*/
if (typeof window !== 'undefined') {
window.mongoose = module.exports;
window.Buffer = Buffer;
}

117
node_modules/mongoose/lib/browserDocument.js generated vendored Normal file
View File

@@ -0,0 +1,117 @@
/*!
* Module dependencies.
*/
var NodeJSDocument = require('./document')
, EventEmitter = require('events').EventEmitter
, setMaxListeners = EventEmitter.prototype.setMaxListeners
, MongooseError = require('./error')
, MixedSchema = require('./schema/mixed')
, Schema = require('./schema')
, ObjectId = require('./types/objectid')
, ValidatorError = require('./schematype').ValidatorError
, utils = require('./utils')
, clone = utils.clone
, isMongooseObject = utils.isMongooseObject
, inspect = require('util').inspect
, ValidationError = MongooseError.ValidationError
, InternalCache = require('./internal')
, deepEqual = utils.deepEqual
, hooks = require('hooks-fixed')
, Promise = require('./promise')
, DocumentArray
, MongooseArray
, Embedded
/**
* Document constructor.
*
* @param {Object} obj the values to set
* @param {Object} [fields] optional object containing the fields which were selected in the query returning this document and any populated paths data
* @param {Boolean} [skipId] bool, should we auto create an ObjectId _id
* @inherits NodeJS EventEmitter http://nodejs.org/api/events.html#events_class_events_eventemitter
* @event `init`: Emitted on a document after it has was retreived from the db and fully hydrated by Mongoose.
* @event `save`: Emitted when the document is successfully saved
* @api private
*/
function Document (obj, schema, fields, skipId, skipInit) {
if ( !(this instanceof Document) )
return new Document( obj, schema, fields, skipId, skipInit );
if (utils.isObject(schema) && !(schema instanceof Schema)) {
schema = new Schema(schema);
}
// When creating EmbeddedDocument, it already has the schema and he doesn't need the _id
schema = this.schema || schema;
// Generate ObjectId if it is missing, but it requires a scheme
if ( !this.schema && schema.options._id ){
obj = obj || {};
if ( obj._id === undefined ){
obj._id = new ObjectId();
}
}
if ( !schema ){
throw new MongooseError.MissingSchemaError();
}
this.$__setSchema(schema);
this.$__ = new InternalCache;
this.$__.emitter = new EventEmitter();
this.isNew = true;
this.errors = undefined;
//var schema = this.schema;
if ('boolean' === typeof fields) {
this.$__.strictMode = fields;
fields = undefined;
} else {
this.$__.strictMode = this.schema.options && this.schema.options.strict;
this.$__.selected = fields;
}
var required = this.schema.requiredPaths();
for (var i = 0; i < required.length; ++i) {
this.$__.activePaths.require(required[i]);
}
setMaxListeners.call(this, 0);
this._doc = this.$__buildDoc(obj, fields, skipId);
if ( !skipInit && obj ){
this.init( obj );
}
this.$__registerHooksFromSchema();
// apply methods
for ( var m in schema.methods ){
this[ m ] = schema.methods[ m ];
}
// apply statics
for ( var s in schema.statics ){
this[ s ] = schema.statics[ s ];
}
}
/*!
* Inherit from the NodeJS document
*/
Document.prototype = Object.create(NodeJSDocument.prototype);
Document.prototype.constructor = Document;
/*!
* Module exports.
*/
Document.ValidationError = ValidationError;
module.exports = exports = Document;

207
node_modules/mongoose/lib/cast.js generated vendored Normal file
View File

@@ -0,0 +1,207 @@
/*!
* Module dependencies.
*/
var utils = require('./utils');
var Types = require('./schema/index');
/**
* Handles internal casting for queries
*
* @param {Schema} schema
* @param {Object obj Object to cast
* @api private
*/
var cast = module.exports = function(schema, obj) {
var paths = Object.keys(obj)
, i = paths.length
, any$conditionals
, schematype
, nested
, path
, type
, val;
while (i--) {
path = paths[i];
val = obj[path];
if ('$or' === path || '$nor' === path || '$and' === path) {
var k = val.length;
var orComponentQuery;
while (k--) {
val[k] = cast(schema, val[k]);
}
} else if (path === '$where') {
type = typeof val;
if ('string' !== type && 'function' !== type) {
throw new Error("Must have a string or function for $where");
}
if ('function' === type) {
obj[path] = val.toString();
}
continue;
} else {
if (!schema) {
// no casting for Mixed types
continue;
}
schematype = schema.path(path);
if (!schematype) {
// Handle potential embedded array queries
var split = path.split('.')
, j = split.length
, pathFirstHalf
, pathLastHalf
, remainingConds
, castingQuery;
// Find the part of the var path that is a path of the Schema
while (j--) {
pathFirstHalf = split.slice(0, j).join('.');
schematype = schema.path(pathFirstHalf);
if (schematype) break;
}
// If a substring of the input path resolves to an actual real path...
if (schematype) {
// Apply the casting; similar code for $elemMatch in schema/array.js
if (schematype.caster && schematype.caster.schema) {
remainingConds = {};
pathLastHalf = split.slice(j).join('.');
remainingConds[pathLastHalf] = val;
obj[path] = cast(schematype.caster.schema, remainingConds)[pathLastHalf];
} else {
obj[path] = val;
}
continue;
}
if (utils.isObject(val)) {
// handle geo schemas that use object notation
// { loc: { long: Number, lat: Number }
var geo = val.$near ? '$near' :
val.$nearSphere ? '$nearSphere' :
val.$within ? '$within' :
val.$geoIntersects ? '$geoIntersects' : '';
if (!geo) {
continue;
}
var numbertype = new Types.Number('__QueryCasting__')
var value = val[geo];
if (val.$maxDistance) {
val.$maxDistance = numbertype.castForQuery(val.$maxDistance);
}
if ('$within' == geo) {
var withinType = value.$center
|| value.$centerSphere
|| value.$box
|| value.$polygon;
if (!withinType) {
throw new Error('Bad $within paramater: ' + JSON.stringify(val));
}
value = withinType;
} else if ('$near' == geo &&
'string' == typeof value.type && Array.isArray(value.coordinates)) {
// geojson; cast the coordinates
value = value.coordinates;
} else if (('$near' == geo || '$nearSphere' == geo || '$geoIntersects' == geo) &&
value.$geometry && 'string' == typeof value.$geometry.type &&
Array.isArray(value.$geometry.coordinates)) {
// geojson; cast the coordinates
value = value.$geometry.coordinates;
}
;(function _cast (val) {
if (Array.isArray(val)) {
val.forEach(function (item, i) {
if (Array.isArray(item) || utils.isObject(item)) {
return _cast(item);
}
val[i] = numbertype.castForQuery(item);
});
} else {
var nearKeys= Object.keys(val);
var nearLen = nearKeys.length;
while (nearLen--) {
var nkey = nearKeys[nearLen];
var item = val[nkey];
if (Array.isArray(item) || utils.isObject(item)) {
_cast(item);
val[nkey] = item;
} else {
val[nkey] = numbertype.castForQuery(item);
}
}
}
})(value);
}
} else if (val === null || val === undefined) {
continue;
} else if ('Object' === val.constructor.name) {
any$conditionals = Object.keys(val).some(function (k) {
return k.charAt(0) === '$' && k !== '$id' && k !== '$ref';
});
if (!any$conditionals) {
obj[path] = schematype.castForQuery(val);
} else {
var ks = Object.keys(val)
, k = ks.length
, $cond;
while (k--) {
$cond = ks[k];
nested = val[$cond];
if ('$exists' === $cond) {
if ('boolean' !== typeof nested) {
throw new Error("$exists parameter must be Boolean");
}
continue;
}
if ('$type' === $cond) {
if ('number' !== typeof nested) {
throw new Error("$type parameter must be Number");
}
continue;
}
if ('$not' === $cond) {
cast(schema, nested);
} else {
val[$cond] = schematype.castForQuery($cond, nested);
}
}
}
} else {
obj[path] = schematype.castForQuery(val);
}
}
}
return obj;
}

198
node_modules/mongoose/lib/collection.js generated vendored Normal file
View File

@@ -0,0 +1,198 @@
/*!
* Module dependencies.
*/
var STATES = require('./connectionstate')
/**
* Abstract Collection constructor
*
* This is the base class that drivers inherit from and implement.
*
* @param {String} name name of the collection
* @param {Connection} conn A MongooseConnection instance
* @param {Object} opts optional collection options
* @api public
*/
function Collection (name, conn, opts) {
if (undefined === opts) opts = {};
if (undefined === opts.capped) opts.capped = {};
opts.bufferCommands = undefined === opts.bufferCommands
? true
: opts.bufferCommands;
if ('number' == typeof opts.capped) {
opts.capped = { size: opts.capped };
}
this.opts = opts;
this.name = name;
this.collectionName = name;
this.conn = conn;
this.queue = [];
this.buffer = this.opts.bufferCommands;
if (STATES.connected == this.conn.readyState) {
this.onOpen();
}
};
/**
* The collection name
*
* @api public
* @property name
*/
Collection.prototype.name;
/**
* The collection name
*
* @api public
* @property collectionName
*/
Collection.prototype.collectionName;
/**
* The Connection instance
*
* @api public
* @property conn
*/
Collection.prototype.conn;
/**
* Called when the database connects
*
* @api private
*/
Collection.prototype.onOpen = function () {
var self = this;
this.buffer = false;
self.doQueue();
};
/**
* Called when the database disconnects
*
* @api private
*/
Collection.prototype.onClose = function () {
if (this.opts.bufferCommands) {
this.buffer = true;
}
};
/**
* Queues a method for later execution when its
* database connection opens.
*
* @param {String} name name of the method to queue
* @param {Array} args arguments to pass to the method when executed
* @api private
*/
Collection.prototype.addQueue = function (name, args) {
this.queue.push([name, args]);
return this;
};
/**
* Executes all queued methods and clears the queue.
*
* @api private
*/
Collection.prototype.doQueue = function () {
for (var i = 0, l = this.queue.length; i < l; i++){
this[this.queue[i][0]].apply(this, this.queue[i][1]);
}
this.queue = [];
return this;
};
/**
* Abstract method that drivers must implement.
*/
Collection.prototype.ensureIndex = function(){
throw new Error('Collection#ensureIndex unimplemented by driver');
};
/**
* Abstract method that drivers must implement.
*/
Collection.prototype.findAndModify = function(){
throw new Error('Collection#findAndModify unimplemented by driver');
};
/**
* Abstract method that drivers must implement.
*/
Collection.prototype.findOne = function(){
throw new Error('Collection#findOne unimplemented by driver');
};
/**
* Abstract method that drivers must implement.
*/
Collection.prototype.find = function(){
throw new Error('Collection#find unimplemented by driver');
};
/**
* Abstract method that drivers must implement.
*/
Collection.prototype.insert = function(){
throw new Error('Collection#insert unimplemented by driver');
};
/**
* Abstract method that drivers must implement.
*/
Collection.prototype.save = function(){
throw new Error('Collection#save unimplemented by driver');
};
/**
* Abstract method that drivers must implement.
*/
Collection.prototype.update = function(){
throw new Error('Collection#update unimplemented by driver');
};
/**
* Abstract method that drivers must implement.
*/
Collection.prototype.getIndexes = function(){
throw new Error('Collection#getIndexes unimplemented by driver');
};
/**
* Abstract method that drivers must implement.
*/
Collection.prototype.mapReduce = function(){
throw new Error('Collection#mapReduce unimplemented by driver');
};
/*!
* Module exports.
*/
module.exports = Collection;

700
node_modules/mongoose/lib/connection.js generated vendored Normal file
View File

@@ -0,0 +1,700 @@
/*!
* Module dependencies.
*/
var url = require('url')
, utils = require('./utils')
, EventEmitter = require('events').EventEmitter
, driver = global.MONGOOSE_DRIVER_PATH || 'node-mongodb-native'
, Model = require('./model')
, Schema = require('./schema')
, Collection = require('./drivers/' + driver + '/collection')
, STATES = require('./connectionstate')
, MongooseError = require('./error')
, assert =require('assert')
, muri = require('muri')
/*!
* Protocol prefix regexp.
*
* @api private
*/
var rgxProtocol = /^(?:.)+:\/\//;
/**
* Connection constructor
*
* For practical reasons, a Connection equals a Db.
*
* @param {Mongoose} base a mongoose instance
* @inherits NodeJS EventEmitter http://nodejs.org/api/events.html#events_class_events_eventemitter
* @event `connecting`: Emitted when `connection.{open,openSet}()` is executed on this connection.
* @event `connected`: Emitted when this connection successfully connects to the db. May be emitted _multiple_ times in `reconnected` scenarios.
* @event `open`: Emitted after we `connected` and `onOpen` is executed on all of this connections models.
* @event `disconnecting`: Emitted when `connection.close()` was executed.
* @event `disconnected`: Emitted after getting disconnected from the db.
* @event `close`: Emitted after we `disconnected` and `onClose` executed on all of this connections models.
* @event `reconnected`: Emitted after we `connected` and subsequently `disconnected`, followed by successfully another successfull connection.
* @event `error`: Emitted when an error occurs on this connection.
* @event `fullsetup`: Emitted in a replica-set scenario, when all nodes specified in the connection string are connected.
* @api public
*/
function Connection (base) {
this.base = base;
this.collections = {};
this.models = {};
this.config = {autoIndex: true};
this.replica = false;
this.hosts = null;
this.host = null;
this.port = null;
this.user = null;
this.pass = null;
this.name = null;
this.options = null;
this.otherDbs = [];
this._readyState = STATES.disconnected;
this._closeCalled = false;
this._hasOpened = false;
};
/*!
* Inherit from EventEmitter
*/
Connection.prototype.__proto__ = EventEmitter.prototype;
/**
* Connection ready state
*
* - 0 = disconnected
* - 1 = connected
* - 2 = connecting
* - 3 = disconnecting
*
* Each state change emits its associated event name.
*
* ####Example
*
* conn.on('connected', callback);
* conn.on('disconnected', callback);
*
* @property readyState
* @api public
*/
Object.defineProperty(Connection.prototype, 'readyState', {
get: function(){ return this._readyState; }
, set: function (val) {
if (!(val in STATES)) {
throw new Error('Invalid connection state: ' + val);
}
if (this._readyState !== val) {
this._readyState = val;
// loop over the otherDbs on this connection and change their state
for (var i=0; i < this.otherDbs.length; i++) {
this.otherDbs[i].readyState = val;
}
if (STATES.connected === val)
this._hasOpened = true;
this.emit(STATES[val]);
}
}
});
/**
* A hash of the collections associated with this connection
*
* @property collections
*/
Connection.prototype.collections;
/**
* The mongodb.Db instance, set when the connection is opened
*
* @property db
*/
Connection.prototype.db;
/**
* A hash of the global options that are associated with this connection
*
* @property global
*/
Connection.prototype.config;
/**
* Opens the connection to MongoDB.
*
* `options` is a hash with the following possible properties:
*
* config - passed to the connection config instance
* db - passed to the connection db instance
* server - passed to the connection server instance(s)
* replset - passed to the connection ReplSet instance
* user - username for authentication
* pass - password for authentication
* auth - options for authentication (see http://mongodb.github.com/node-mongodb-native/api-generated/db.html#authenticate)
*
* ####Notes:
*
* Mongoose forces the db option `forceServerObjectId` false and cannot be overridden.
* Mongoose defaults the server `auto_reconnect` options to true which can be overridden.
* See the node-mongodb-native driver instance for options that it understands.
*
* _Options passed take precedence over options included in connection strings._
*
* @param {String} connection_string mongodb://uri or the host to which you are connecting
* @param {String} [database] database name
* @param {Number} [port] database port
* @param {Object} [options] options
* @param {Function} [callback]
* @see node-mongodb-native https://github.com/mongodb/node-mongodb-native
* @see http://mongodb.github.com/node-mongodb-native/api-generated/db.html#authenticate
* @api public
*/
Connection.prototype.open = function (host, database, port, options, callback) {
var self = this
, parsed
, uri;
if ('string' === typeof database) {
switch (arguments.length) {
case 2:
port = 27017;
case 3:
switch (typeof port) {
case 'function':
callback = port, port = 27017;
break;
case 'object':
options = port, port = 27017;
break;
}
break;
case 4:
if ('function' === typeof options)
callback = options, options = {};
}
} else {
switch (typeof database) {
case 'function':
callback = database, database = undefined;
break;
case 'object':
options = database;
database = undefined;
callback = port;
break;
}
if (!rgxProtocol.test(host)) {
host = 'mongodb://' + host;
}
try {
parsed = muri(host);
} catch (err) {
this.error(err, callback);
return this;
}
database = parsed.db;
host = parsed.hosts[0].host || parsed.hosts[0].ipc;
port = parsed.hosts[0].port || 27017;
}
this.options = this.parseOptions(options, parsed && parsed.options);
// make sure we can open
if (STATES.disconnected !== this.readyState) {
var err = new Error('Trying to open unclosed connection.');
err.state = this.readyState;
this.error(err, callback);
return this;
}
if (!host) {
this.error(new Error('Missing hostname.'), callback);
return this;
}
if (!database) {
this.error(new Error('Missing database name.'), callback);
return this;
}
// authentication
if (options && options.user && options.pass) {
this.user = options.user;
this.pass = options.pass;
} else if (parsed && parsed.auth) {
this.user = parsed.auth.user;
this.pass = parsed.auth.pass;
// Check hostname for user/pass
} else if (/@/.test(host) && /:/.test(host.split('@')[0])) {
host = host.split('@');
var auth = host.shift().split(':');
host = host.pop();
this.user = auth[0];
this.pass = auth[1];
} else {
this.user = this.pass = undefined;
}
// global configuration options
if (options && options.config) {
if (options.config.autoIndex === false){
this.config.autoIndex = false;
}
else {
this.config.autoIndex = true;
}
}
this.name = database;
this.host = host;
this.port = port;
this._open(callback);
return this;
};
/**
* Opens the connection to a replica set.
*
* ####Example:
*
* var db = mongoose.createConnection();
* db.openSet("mongodb://user:pwd@localhost:27020/testing,mongodb://example.com:27020,mongodb://localhost:27019");
*
* The database name and/or auth need only be included in one URI.
* The `options` is a hash which is passed to the internal driver connection object.
*
* Valid `options`
*
* db - passed to the connection db instance
* server - passed to the connection server instance(s)
* replset - passed to the connection ReplSetServer instance
* user - username for authentication
* pass - password for authentication
* auth - options for authentication (see http://mongodb.github.com/node-mongodb-native/api-generated/db.html#authenticate)
* mongos - Boolean - if true, enables High Availability support for mongos
*
* _Options passed take precedence over options included in connection strings._
*
* ####Notes:
*
* _If connecting to multiple mongos servers, set the `mongos` option to true._
*
* conn.open('mongodb://mongosA:27501,mongosB:27501', { mongos: true }, cb);
*
* Mongoose forces the db option `forceServerObjectId` false and cannot be overridden.
* Mongoose defaults the server `auto_reconnect` options to true which can be overridden.
* See the node-mongodb-native driver instance for options that it understands.
*
* _Options passed take precedence over options included in connection strings._
*
* @param {String} uris comma-separated mongodb:// `URI`s
* @param {String} [database] database name if not included in `uris`
* @param {Object} [options] passed to the internal driver
* @param {Function} [callback]
* @see node-mongodb-native https://github.com/mongodb/node-mongodb-native
* @see http://mongodb.github.com/node-mongodb-native/api-generated/db.html#authenticate
* @api public
*/
Connection.prototype.openSet = function (uris, database, options, callback) {
if (!rgxProtocol.test(uris)) {
uris = 'mongodb://' + uris;
}
var self = this;
switch (arguments.length) {
case 3:
switch (typeof database) {
case 'string':
this.name = database;
break;
case 'object':
callback = options;
options = database;
database = null;
break;
}
if ('function' === typeof options) {
callback = options;
options = {};
}
break;
case 2:
switch (typeof database) {
case 'string':
this.name = database;
break;
case 'function':
callback = database, database = null;
break;
case 'object':
options = database, database = null;
break;
}
}
var parsed;
try {
parsed = muri(uris);
} catch (err) {
this.error(err, callback);
return this;
}
if (!this.name) {
this.name = parsed.db;
}
this.hosts = parsed.hosts;
this.options = this.parseOptions(options, parsed && parsed.options);
this.replica = true;
if (!this.name) {
this.error(new Error('No database name provided for replica set'), callback);
return this;
}
// authentication
if (options && options.user && options.pass) {
this.user = options.user;
this.pass = options.pass;
} else if (parsed && parsed.auth) {
this.user = parsed.auth.user;
this.pass = parsed.auth.pass;
} else {
this.user = this.pass = undefined;
}
// global configuration options
if (options && options.config) {
if (options.config.autoIndex === false){
this.config.autoIndex = false;
}
else {
this.config.autoIndex = true;
}
}
this._open(callback);
return this;
};
/**
* error
*
* Graceful error handling, passes error to callback
* if available, else emits error on the connection.
*
* @param {Error} err
* @param {Function} callback optional
* @api private
*/
Connection.prototype.error = function (err, callback) {
if (callback) return callback(err);
this.emit('error', err);
}
/**
* Handles opening the connection with the appropriate method based on connection type.
*
* @param {Function} callback
* @api private
*/
Connection.prototype._open = function (callback) {
this.readyState = STATES.connecting;
this._closeCalled = false;
var self = this;
var method = this.replica
? 'doOpenSet'
: 'doOpen';
// open connection
this[method](function (err) {
if (err) {
self.readyState = STATES.disconnected;
if (self._hasOpened) {
if (callback) callback(err);
} else {
self.error(err, callback);
}
return;
}
self.onOpen(callback);
});
}
/**
* Called when the connection is opened
*
* @api private
*/
Connection.prototype.onOpen = function (callback) {
var self = this;
function open(err, isAuth) {
if (err) {
self.readyState = isAuth ? STATES.unauthorized : STATES.disconnected;
if (self._hasOpened) {
if (callback) callback(err);
} else {
self.error(err, callback);
}
return;
}
self.readyState = STATES.connected;
// avoid having the collection subscribe to our event emitter
// to prevent 0.3 warning
for (var i in self.collections)
self.collections[i].onOpen();
callback && callback();
self.emit('open');
};
// re-authenticate
if (self.user && self.pass) {
self.db.authenticate(self.user, self.pass, self.options.auth, function(err) {
open(err, true);
});
} else {
open();
}
};
/**
* Closes the connection
*
* @param {Function} [callback] optional
* @return {Connection} self
* @api public
*/
Connection.prototype.close = function (callback) {
var self = this;
this._closeCalled = true;
switch (this.readyState){
case 0: // disconnected
callback && callback();
break;
case 1: // connected
case 4: // unauthorized
this.readyState = STATES.disconnecting;
this.doClose(function(err){
if (err){
self.error(err, callback);
} else {
self.onClose();
callback && callback();
}
});
break;
case 2: // connecting
this.once('open', function(){
self.close(callback);
});
break;
case 3: // disconnecting
if (!callback) break;
this.once('close', function () {
callback();
});
break;
}
return this;
};
/**
* Called when the connection closes
*
* @api private
*/
Connection.prototype.onClose = function () {
this.readyState = STATES.disconnected;
// avoid having the collection subscribe to our event emitter
// to prevent 0.3 warning
for (var i in this.collections)
this.collections[i].onClose();
this.emit('close');
};
/**
* Retrieves a collection, creating it if not cached.
*
* Not typically needed by applications. Just talk to your collection through your model.
*
* @param {String} name of the collection
* @param {Object} [options] optional collection options
* @return {Collection} collection instance
* @api public
*/
Connection.prototype.collection = function (name, options) {
if (!(name in this.collections))
this.collections[name] = new Collection(name, this, options);
return this.collections[name];
};
/**
* Defines or retrieves a model.
*
* var mongoose = require('mongoose');
* var db = mongoose.createConnection(..);
* db.model('Venue', new Schema(..));
* var Ticket = db.model('Ticket', new Schema(..));
* var Venue = db.model('Venue');
*
* _When no `collection` argument is passed, Mongoose produces a collection name by passing the model `name` to the [utils.toCollectionName](#utils_exports.toCollectionName) method. This method pluralizes the name. If you don't like this behavior, either pass a collection name or set your schemas collection name option._
*
* ####Example:
*
* var schema = new Schema({ name: String }, { collection: 'actor' });
*
* // or
*
* schema.set('collection', 'actor');
*
* // or
*
* var collectionName = 'actor'
* var M = conn.model('Actor', schema, collectionName)
*
* @param {String} name the model name
* @param {Schema} [schema] a schema. necessary when defining a model
* @param {String} [collection] name of mongodb collection (optional) if not given it will be induced from model name
* @see Mongoose#model #index_Mongoose-model
* @return {Model} The compiled model
* @api public
*/
Connection.prototype.model = function (name, schema, collection) {
// collection name discovery
if ('string' == typeof schema) {
collection = schema;
schema = false;
}
if (utils.isObject(schema) && !(schema instanceof Schema)) {
schema = new Schema(schema);
}
if (this.models[name] && !collection) {
// model exists but we are not subclassing with custom collection
if (schema instanceof Schema && schema != this.models[name].schema) {
throw new MongooseError.OverwriteModelError(name);
}
return this.models[name];
}
var opts = { cache: false, connection: this }
var model;
if (schema instanceof Schema) {
// compile a model
model = this.base.model(name, schema, collection, opts)
// only the first model with this name is cached to allow
// for one-offs with custom collection names etc.
if (!this.models[name]) {
this.models[name] = model;
}
model.init();
return model;
}
if (this.models[name] && collection) {
// subclassing current model with alternate collection
model = this.models[name];
schema = model.prototype.schema;
var sub = model.__subclass(this, schema, collection);
// do not cache the sub model
return sub;
}
// lookup model in mongoose module
model = this.base.models[name];
if (!model) {
throw new MongooseError.MissingSchemaError(name);
}
if (this == model.prototype.db
&& (!collection || collection == model.collection.name)) {
// model already uses this connection.
// only the first model with this name is cached to allow
// for one-offs with custom collection names etc.
if (!this.models[name]) {
this.models[name] = model;
}
return model;
}
return this.models[name] = model.__subclass(this, schema, collection);
};
/**
* Returns an array of model names created on this connection.
* @api public
* @return {Array}
*/
Connection.prototype.modelNames = function () {
return Object.keys(this.models);
};
/*!
* Noop.
*/
function noop () {}
/*!
* Module exports.
*/
Connection.STATES = STATES;
module.exports = Connection;

27
node_modules/mongoose/lib/connectionstate.js generated vendored Normal file
View File

@@ -0,0 +1,27 @@
/*!
* Connection states
*/
var STATES = module.exports = exports = Object.create(null);
var disconnected = 'disconnected';
var connected = 'connected';
var connecting = 'connecting';
var disconnecting = 'disconnecting';
var unauthorized = 'unauthorized';
var uninitialized = 'uninitialized';
STATES[0] = disconnected;
STATES[1] = connected;
STATES[2] = connecting;
STATES[3] = disconnecting;
STATES[4] = unauthorized;
STATES[99] = uninitialized;
STATES[disconnected] = 0;
STATES[connected] = 1;
STATES[connecting] = 2;
STATES[disconnecting] = 3;
STATES[unauthorized] = 4;
STATES[uninitialized] = 99;

2138
node_modules/mongoose/lib/document.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

20
node_modules/mongoose/lib/document_provider.js generated vendored Normal file
View File

@@ -0,0 +1,20 @@
'use strict';
/*!
* Module dependencies.
*/
var Document = require('./document.js');
var BrowserDocument = require('./browserDocument.js');
/**
* Returns the Document constructor for the current context
*
* @api private
*/
module.exports = function() {
if (typeof window !== 'undefined' && typeof document !== 'undefined' && document === window.document) {
return BrowserDocument;
} else {
return Document;
}
};

4
node_modules/mongoose/lib/drivers/SPEC.md generated vendored Normal file
View File

@@ -0,0 +1,4 @@
# Driver Spec
TODO

View File

@@ -0,0 +1,5 @@
/*!
* ignore
*/
module.exports = function() {};

12
node_modules/mongoose/lib/drivers/browser/binary.js generated vendored Normal file
View File

@@ -0,0 +1,12 @@
/*!
* Module dependencies.
*/
var Binary = require('bson').Binary;
/*!
* Module exports.
*/
module.exports = exports = Binary;

7
node_modules/mongoose/lib/drivers/browser/index.js generated vendored Normal file
View File

@@ -0,0 +1,7 @@
/*!
* Module exports.
*/
exports.Binary = require('./binary');
exports.ObjectId = require('./objectid');
exports.ReadPreference = require('./ReadPreference');

14
node_modules/mongoose/lib/drivers/browser/objectid.js generated vendored Normal file
View File

@@ -0,0 +1,14 @@
/*!
* [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) ObjectId
* @constructor NodeMongoDbObjectId
* @see ObjectId
*/
var ObjectId = require('bson').ObjectID;
/*!
* ignore
*/
module.exports = exports = ObjectId;

18
node_modules/mongoose/lib/drivers/index.js generated vendored Normal file
View File

@@ -0,0 +1,18 @@
/*!
* ignore
*/
var driver;
if (typeof window === 'undefined') {
driver = require('./' +
(global.MONGOOSE_DRIVER_PATH || 'node-mongodb-native'));
} else {
driver = require('./browser');
}
/*!
* ignore
*/
module.exports = driver;

View File

@@ -0,0 +1,45 @@
/*!
* Module dependencies.
*/
var mongodb = require('mongodb');
var ReadPref = mongodb.ReadPreference;
/*!
* Converts arguments to ReadPrefs the driver
* can understand.
*
* @param {String|Array} pref
* @param {Array} [tags]
*/
module.exports = function readPref (pref, tags) {
if (Array.isArray(pref)) {
tags = pref[1];
pref = pref[0];
}
if (pref instanceof ReadPref) {
return pref;
}
switch (pref) {
case 'p':
pref = 'primary';
break;
case 'pp':
pref = 'primaryPreferred';
break;
case 's':
pref = 'secondary';
break;
case 'sp':
pref = 'secondaryPreferred';
break;
case 'n':
pref = 'nearest';
break;
}
return new ReadPref(pref, tags);
}

View File

@@ -0,0 +1,8 @@
/*!
* Module dependencies.
*/
var Binary = require('mongodb').Binary;
module.exports = exports = Binary;

View File

@@ -0,0 +1,225 @@
/*!
* Module dependencies.
*/
var MongooseCollection = require('../../collection')
, Collection = require('mongodb').Collection
, STATES = require('../../connectionstate')
, utils = require('../../utils')
/**
* A [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) collection implementation.
*
* All methods methods from the [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) driver are copied and wrapped in queue management.
*
* @inherits Collection
* @api private
*/
function NativeCollection () {
this.collection = null;
MongooseCollection.apply(this, arguments);
}
/*!
* Inherit from abstract Collection.
*/
NativeCollection.prototype.__proto__ = MongooseCollection.prototype;
/**
* Called when the connection opens.
*
* @api private
*/
NativeCollection.prototype.onOpen = function () {
var self = this;
// always get a new collection in case the user changed host:port
// of parent db instance when re-opening the connection.
if (!self.opts.capped.size) {
// non-capped
return self.conn.db.collection(self.name, callback);
}
// capped
return self.conn.db.collection(self.name, function (err, c) {
if (err) return callback(err);
// discover if this collection exists and if it is capped
self.conn.db.listCollections({ name: self.name }).toArray(function(err, docs) {
if (err) {
return callback(err);
}
var doc = docs[0];
var exists = !!doc;
if (exists) {
if (doc.options && doc.options.capped) {
callback(null, c);
} else {
var msg = 'A non-capped collection exists with the name: '+ self.name +'\n\n'
+ ' To use this collection as a capped collection, please '
+ 'first convert it.\n'
+ ' http://www.mongodb.org/display/DOCS/Capped+Collections#CappedCollections-Convertingacollectiontocapped'
err = new Error(msg);
callback(err);
}
} else {
// create
var opts = utils.clone(self.opts.capped);
opts.capped = true;
self.conn.db.createCollection(self.name, opts, callback);
}
});
});
function callback (err, collection) {
if (err) {
// likely a strict mode error
self.conn.emit('error', err);
} else {
self.collection = collection;
MongooseCollection.prototype.onOpen.call(self);
}
};
};
/**
* Called when the connection closes
*
* @api private
*/
NativeCollection.prototype.onClose = function () {
MongooseCollection.prototype.onClose.call(this);
};
/*!
* Copy the collection methods and make them subject to queues
*/
for (var i in Collection.prototype) {
// Janky hack to work around gh-3005 until we can get rid of the mongoose
// collection abstraction
try {
if (typeof Collection.prototype[i] !== 'function') {
continue;
}
} catch(e) {
continue;
}
(function(i){
NativeCollection.prototype[i] = function () {
if (this.buffer) {
this.addQueue(i, arguments);
return;
}
var collection = this.collection
, args = arguments
, self = this
, debug = self.conn.base.options.debug;
if (debug) {
if ('function' === typeof debug) {
debug.apply(debug
, [self.name, i].concat(utils.args(args, 0, args.length-1)));
} else {
console.error('\x1B[0;36mMongoose:\x1B[0m %s.%s(%s) %s %s %s'
, self.name
, i
, print(args[0])
, print(args[1])
, print(args[2])
, print(args[3]))
}
}
return collection[i].apply(collection, args);
};
})(i);
}
/*!
* Debug print helper
*/
function print (arg) {
var type = typeof arg;
if ('function' === type || 'undefined' === type) return '';
return format(arg);
}
/*!
* Debug print helper
*/
function format (obj, sub) {
var x = utils.clone(obj, { retainKeyOrder: 1 });
if (x) {
if ('Binary' === x.constructor.name) {
x = '[object Buffer]';
} else if ('ObjectID' === x.constructor.name) {
var representation = 'ObjectId("' + x.toHexString() + '")';
x = { inspect: function() { return representation; } };
} else if ('Date' === x.constructor.name) {
var representation = 'new Date("' + x.toUTCString() + '")';
x = { inspect: function() { return representation; } };
} else if ('Object' === x.constructor.name) {
var keys = Object.keys(x);
var numKeys = keys.length;
var key;
for (var i = 0; i < numKeys; ++i) {
key = keys[i];
if (x[key]) {
if ('Binary' === x[key].constructor.name) {
x[key] = '[object Buffer]';
} else if ('Object' === x[key].constructor.name) {
x[key] = format(x[key], true);
} else if ('ObjectID' === x[key].constructor.name) {
;(function(x){
var representation = 'ObjectId("' + x[key].toHexString() + '")';
x[key] = { inspect: function() { return representation; } };
})(x)
} else if ('Date' === x[key].constructor.name) {
;(function(x){
var representation = 'new Date("' + x[key].toUTCString() + '")';
x[key] = { inspect: function() { return representation; } };
})(x)
} else if (Array.isArray(x[key])) {
x[key] = x[key].map(function (o) {
return format(o, true)
});
}
}
}
}
if (sub) return x;
}
return require('util')
.inspect(x, false, 10, true)
.replace(/\n/g, '')
.replace(/\s{2,}/g, ' ')
}
/**
* Retreives information about this collections indexes.
*
* @param {Function} callback
* @method getIndexes
* @api public
*/
NativeCollection.prototype.getIndexes = NativeCollection.prototype.indexInformation;
/*!
* Module exports.
*/
module.exports = NativeCollection;

View File

@@ -0,0 +1,378 @@
/*!
* Module dependencies.
*/
var MongooseConnection = require('../../connection')
, mongo = require('mongodb')
, Db = mongo.Db
, Server = mongo.Server
, Mongos = mongo.Mongos
, STATES = require('../../connectionstate')
, ReplSetServers = mongo.ReplSet
, utils = require('../../utils');
/**
* A [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) connection implementation.
*
* @inherits Connection
* @api private
*/
function NativeConnection() {
MongooseConnection.apply(this, arguments);
this._listening = false;
};
/**
* Expose the possible connection states.
* @api public
*/
NativeConnection.STATES = STATES;
/*!
* Inherits from Connection.
*/
NativeConnection.prototype.__proto__ = MongooseConnection.prototype;
/**
* Opens the connection to MongoDB.
*
* @param {Function} fn
* @return {Connection} this
* @api private
*/
NativeConnection.prototype.doOpen = function (fn) {
if (this.db) {
mute(this);
}
var server = new Server(this.host, this.port, this.options.server);
this.db = new Db(this.name, server, this.options.db);
var self = this;
this.db.open(function (err) {
if (err) return fn(err);
listen(self);
fn();
});
return this;
};
/**
* Switches to a different database using the same connection pool.
*
* Returns a new connection object, with the new db.
*
* @param {String} name The database name
* @return {Connection} New Connection Object
* @api public
*/
NativeConnection.prototype.useDb = function (name) {
// we have to manually copy all of the attributes...
var newConn = new this.constructor();
newConn.name = name;
newConn.base = this.base;
newConn.collections = {};
newConn.models = {};
newConn.replica = this.replica;
newConn.hosts = this.hosts;
newConn.host = this.host;
newConn.port = this.port;
newConn.user = this.user;
newConn.pass = this.pass;
newConn.options = this.options;
newConn._readyState = this._readyState;
newConn._closeCalled = this._closeCalled;
newConn._hasOpened = this._hasOpened;
newConn._listening = false;
// First, when we create another db object, we are not guaranteed to have a
// db object to work with. So, in the case where we have a db object and it
// is connected, we can just proceed with setting everything up. However, if
// we do not have a db or the state is not connected, then we need to wait on
// the 'open' event of the connection before doing the rest of the setup
// the 'connected' event is the first time we'll have access to the db object
var self = this;
if (this.db && this._readyState === STATES.connected) {
wireup();
} else {
this.once('connected', wireup);
}
function wireup () {
newConn.db = self.db.db(name);
newConn.onOpen();
// setup the events appropriately
listen(newConn);
}
newConn.name = name;
// push onto the otherDbs stack, this is used when state changes
this.otherDbs.push(newConn);
newConn.otherDbs.push(this);
return newConn;
};
/*!
* Register listeners for important events and bubble appropriately.
*/
function listen (conn) {
if (conn._listening) return;
conn._listening = true;
conn.db.on('close', function(){
if (conn._closeCalled) return;
// the driver never emits an `open` event. auto_reconnect still
// emits a `close` event but since we never get another
// `open` we can't emit close
if (conn.db.serverConfig.autoReconnect) {
conn.readyState = STATES.disconnected;
conn.emit('close');
return;
}
conn.onClose();
});
conn.db.on('error', function(err){
conn.emit('error', err);
});
conn.db.on('reconnect', function() {
conn.readyState = STATES.connected;
conn.emit('reconnected');
});
conn.db.on('timeout', function(err){
var error = new Error(err && err.err || 'connection timeout');
conn.emit('error', error);
});
conn.db.on('open', function (err, db) {
if (STATES.disconnected === conn.readyState && db && db.databaseName) {
conn.readyState = STATES.connected;
conn.emit('reconnected');
}
});
conn.db.on('parseError', function(err) {
conn.emit('parseError', err);
});
}
/*!
* Remove listeners registered in `listen`
*/
function mute (conn) {
if (!conn.db) throw new Error('missing db');
conn.db.removeAllListeners("close");
conn.db.removeAllListeners("error");
conn.db.removeAllListeners("timeout");
conn.db.removeAllListeners("open");
conn.db.removeAllListeners("fullsetup");
conn._listening = false;
}
/**
* Opens a connection to a MongoDB ReplicaSet.
*
* See description of [doOpen](#NativeConnection-doOpen) for server options. In this case `options.replset` is also passed to ReplSetServers.
*
* @param {Function} fn
* @api private
* @return {Connection} this
*/
NativeConnection.prototype.doOpenSet = function (fn) {
if (this.db) {
mute(this);
}
var servers = []
, self = this;
this.hosts.forEach(function (server) {
var host = server.host || server.ipc;
var port = server.port || 27017;
servers.push(new Server(host, port, self.options.server));
})
var server = this.options.mongos
? new Mongos(servers, this.options.mongos)
: new ReplSetServers(servers, this.options.replset);
this.db = new Db(this.name, server, this.options.db);
this.db.on('fullsetup', function () {
self.emit('fullsetup')
});
this.db.open(function (err) {
if (err) return fn(err);
fn();
listen(self);
});
return this;
};
/**
* Closes the connection
*
* @param {Function} fn
* @return {Connection} this
* @api private
*/
NativeConnection.prototype.doClose = function (fn) {
this.db.close();
if (fn) fn();
return this;
}
/**
* Prepares default connection options for the node-mongodb-native driver.
*
* _NOTE: `passed` options take precedence over connection string options._
*
* @param {Object} passed options that were passed directly during connection
* @param {Object} [connStrOptions] options that were passed in the connection string
* @api private
*/
NativeConnection.prototype.parseOptions = function (passed, connStrOpts) {
var o = passed || {};
o.db || (o.db = {});
o.auth || (o.auth = {});
o.server || (o.server = {});
o.replset || (o.replset = {});
o.server.socketOptions || (o.server.socketOptions = {});
o.replset.socketOptions || (o.replset.socketOptions = {});
var opts = connStrOpts || {};
Object.keys(opts).forEach(function (name) {
switch (name) {
case 'ssl':
case 'poolSize':
if ('undefined' == typeof o.server[name]) {
o.server[name] = o.replset[name] = opts[name];
}
break;
case 'slaveOk':
if ('undefined' == typeof o.server.slave_ok) {
o.server.slave_ok = opts[name];
}
break;
case 'autoReconnect':
if ('undefined' == typeof o.server.auto_reconnect) {
o.server.auto_reconnect = opts[name];
}
break;
case 'socketTimeoutMS':
case 'connectTimeoutMS':
if ('undefined' == typeof o.server.socketOptions[name]) {
o.server.socketOptions[name] = o.replset.socketOptions[name] = opts[name];
}
break;
case 'authdb':
if ('undefined' == typeof o.auth.authdb) {
o.auth.authdb = opts[name];
}
break;
case 'authSource':
if ('undefined' == typeof o.auth.authSource) {
o.auth.authSource = opts[name];
}
break;
case 'retries':
case 'reconnectWait':
case 'rs_name':
if ('undefined' == typeof o.replset[name]) {
o.replset[name] = opts[name];
}
break;
case 'replicaSet':
if ('undefined' == typeof o.replset.rs_name) {
o.replset.rs_name = opts[name];
}
break;
case 'readSecondary':
if ('undefined' == typeof o.replset.read_secondary) {
o.replset.read_secondary = opts[name];
}
break;
case 'nativeParser':
if ('undefined' == typeof o.db.native_parser) {
o.db.native_parser = opts[name];
}
break;
case 'w':
case 'safe':
case 'fsync':
case 'journal':
case 'wtimeoutMS':
if ('undefined' == typeof o.db[name]) {
o.db[name] = opts[name];
}
break;
case 'readPreference':
if ('undefined' == typeof o.db.read_preference) {
o.db.read_preference = opts[name];
}
break;
case 'readPreferenceTags':
if ('undefined' == typeof o.db.read_preference_tags) {
o.db.read_preference_tags = opts[name];
}
break;
}
})
if (!('auto_reconnect' in o.server)) {
o.server.auto_reconnect = true;
}
if (!o.db.read_preference) {
// read from primaries by default
o.db.read_preference = 'primary';
}
// mongoose creates its own ObjectIds
o.db.forceServerObjectId = false;
// default safe using new nomenclature
if (!('journal' in o.db || 'j' in o.db ||
'fsync' in o.db || 'safe' in o.db || 'w' in o.db)) {
o.db.w = 1;
}
validate(o);
return o;
}
/*!
* Validates the driver db options.
*
* @param {Object} o
*/
function validate (o) {
if (-1 === o.db.w || 0 === o.db.w) {
if (o.db.journal || o.db.fsync || o.db.safe) {
throw new Error(
'Invalid writeConcern: '
+ 'w set to -1 or 0 cannot be combined with safe|fsync|journal');
}
}
}
/*!
* Module exports.
*/
module.exports = NativeConnection;

View File

@@ -0,0 +1,7 @@
/*!
* Module exports.
*/
exports.Binary = require('./binary');
exports.ObjectId = require('./objectid');
exports.ReadPreference = require('./ReadPreference');

View File

@@ -0,0 +1,14 @@
/*!
* [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) ObjectId
* @constructor NodeMongoDbObjectId
* @see ObjectId
*/
var ObjectId = require('mongodb').ObjectId;
/*!
* ignore
*/
module.exports = exports = ObjectId;

51
node_modules/mongoose/lib/error.js generated vendored Normal file
View File

@@ -0,0 +1,51 @@
/**
* MongooseError constructor
*
* @param {String} msg Error message
* @inherits Error https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error
*/
function MongooseError (msg) {
Error.call(this);
this.stack = new Error().stack;
this.message = msg;
this.name = 'MongooseError';
};
/*!
* Inherits from Error.
*/
MongooseError.prototype = Object.create(Error.prototype);
MongooseError.prototype.constructor = Error;
/*!
* Module exports.
*/
module.exports = exports = MongooseError;
/**
* The default built-in validator error messages.
*
* @see Error.messages #error_messages_MongooseError-messages
* @api public
*/
MongooseError.messages = require('./error/messages');
// backward compat
MongooseError.Messages = MongooseError.messages;
/*!
* Expose subclasses
*/
MongooseError.CastError = require('./error/cast');
MongooseError.ValidationError = require('./error/validation')
MongooseError.ValidatorError = require('./error/validator')
MongooseError.VersionError =require('./error/version')
MongooseError.OverwriteModelError = require('./error/overwriteModel')
MongooseError.MissingSchemaError = require('./error/missingSchema')
MongooseError.DivergentArrayError = require('./error/divergentArray')

View File

@@ -0,0 +1,33 @@
/*!
* Module dependencies.
*/
var MongooseError = require('../error.js');
/*!
* MissingSchema Error constructor.
*
* @inherits MongooseError
*/
function MissingSchemaError (name) {
var msg = 'Schema hasn\'t been registered for document.\n'
+ 'Use mongoose.Document(name, schema)';
MongooseError.call(this, msg);
Error.captureStackTrace && Error.captureStackTrace(this, arguments.callee);
this.name = 'MissingSchemaError';
}
/*!
* Inherits from MongooseError.
*/
MissingSchemaError.prototype = Object.create(MongooseError.prototype);
MissingSchemaError.prototype.constructor = MongooseError;
/*!
* exports
*/
module.exports = MissingSchemaError;

37
node_modules/mongoose/lib/error/cast.js generated vendored Normal file
View File

@@ -0,0 +1,37 @@
/*!
* Module dependencies.
*/
var MongooseError = require('../error.js');
/**
* Casting Error constructor.
*
* @param {String} type
* @param {String} value
* @inherits MongooseError
* @api private
*/
function CastError (type, value, path) {
MongooseError.call(this, 'Cast to ' + type + ' failed for value "' + value + '" at path "' + path + '"');
Error.captureStackTrace && Error.captureStackTrace(this, arguments.callee);
this.name = 'CastError';
this.kind = type;
this.value = value;
this.path = path;
};
/*!
* Inherits from MongooseError.
*/
CastError.prototype = Object.create(MongooseError.prototype);
CastError.prototype.constructor = MongooseError;
/*!
* exports
*/
module.exports = CastError;

42
node_modules/mongoose/lib/error/divergentArray.js generated vendored Normal file
View File

@@ -0,0 +1,42 @@
/*!
* Module dependencies.
*/
var MongooseError = require('../error.js');
/*!
* DivergentArrayError constructor.
*
* @inherits MongooseError
*/
function DivergentArrayError (paths) {
var msg = 'For your own good, using `document.save()` to update an array '
+ 'which was selected using an $elemMatch projection OR '
+ 'populated using skip, limit, query conditions, or exclusion of '
+ 'the _id field when the operation results in a $pop or $set of '
+ 'the entire array is not supported. The following '
+ 'path(s) would have been modified unsafely:\n'
+ ' ' + paths.join('\n ') + '\n'
+ 'Use Model.update() to update these arrays instead.'
// TODO write up a docs page (FAQ) and link to it
MongooseError.call(this, msg);
Error.captureStackTrace && Error.captureStackTrace(this, arguments.callee);
this.name = 'DivergentArrayError';
};
/*!
* Inherits from MongooseError.
*/
DivergentArrayError.prototype = Object.create(MongooseError.prototype);
DivergentArrayError.prototype.constructor = MongooseError;
/*!
* exports
*/
module.exports = DivergentArrayError;

43
node_modules/mongoose/lib/error/messages.js generated vendored Normal file
View File

@@ -0,0 +1,43 @@
/**
* The default built-in validator error messages. These may be customized.
*
* // customize within each schema or globally like so
* var mongoose = require('mongoose');
* mongoose.Error.messages.String.enum = "Your custom message for {PATH}.";
*
* As you might have noticed, error messages support basic templating
*
* - `{PATH}` is replaced with the invalid document path
* - `{VALUE}` is replaced with the invalid value
* - `{TYPE}` is replaced with the validator type such as "regexp", "min", or "user defined"
* - `{MIN}` is replaced with the declared min value for the Number.min validator
* - `{MAX}` is replaced with the declared max value for the Number.max validator
*
* Click the "show code" link below to see all defaults.
*
* @property messages
* @receiver MongooseError
* @api public
*/
var msg = module.exports = exports = {};
msg.general = {};
msg.general.default = "Validator failed for path `{PATH}` with value `{VALUE}`";
msg.general.required = "Path `{PATH}` is required.";
msg.Number = {};
msg.Number.min = "Path `{PATH}` ({VALUE}) is less than minimum allowed value ({MIN}).";
msg.Number.max = "Path `{PATH}` ({VALUE}) is more than maximum allowed value ({MAX}).";
msg.Date = {};
msg.Date.min = "Path `{PATH}` ({VALUE}) is before minimum allowed value ({MIN}).";
msg.Date.max = "Path `{PATH}` ({VALUE}) is after maximum allowed value ({MAX}).";
msg.String = {};
msg.String.enum = "`{VALUE}` is not a valid enum value for path `{PATH}`.";
msg.String.match = "Path `{PATH}` is invalid ({VALUE}).";
msg.String.minlength = "Path `{PATH}` (`{VALUE}`) is shorter than the minimum allowed length ({MINLENGTH}).";
msg.String.maxlength = "Path `{PATH}` (`{VALUE}`) is longer than the maximum allowed length ({MAXLENGTH}).";

33
node_modules/mongoose/lib/error/missingSchema.js generated vendored Normal file
View File

@@ -0,0 +1,33 @@
/*!
* Module dependencies.
*/
var MongooseError = require('../error.js');
/*!
* MissingSchema Error constructor.
*
* @inherits MongooseError
*/
function MissingSchemaError (name) {
var msg = 'Schema hasn\'t been registered for model "' + name + '".\n'
+ 'Use mongoose.model(name, schema)';
MongooseError.call(this, msg);
Error.captureStackTrace && Error.captureStackTrace(this, arguments.callee);
this.name = 'MissingSchemaError';
}
/*!
* Inherits from MongooseError.
*/
MissingSchemaError.prototype = Object.create(MongooseError.prototype);
MissingSchemaError.prototype.constructor = MongooseError;
/*!
* exports
*/
module.exports = MissingSchemaError;

31
node_modules/mongoose/lib/error/overwriteModel.js generated vendored Normal file
View File

@@ -0,0 +1,31 @@
/*!
* Module dependencies.
*/
var MongooseError = require('../error.js');
/*!
* OverwriteModel Error constructor.
*
* @inherits MongooseError
*/
function OverwriteModelError (name) {
MongooseError.call(this, 'Cannot overwrite `' + name + '` model once compiled.');
Error.captureStackTrace && Error.captureStackTrace(this, arguments.callee);
this.name = 'OverwriteModelError';
};
/*!
* Inherits from MongooseError.
*/
OverwriteModelError.prototype = Object.create(MongooseError.prototype);
OverwriteModelError.prototype.constructor = MongooseError;
/*!
* exports
*/
module.exports = OverwriteModelError;

58
node_modules/mongoose/lib/error/validation.js generated vendored Normal file
View File

@@ -0,0 +1,58 @@
/*!
* Module requirements
*/
var MongooseError = require('../error.js');
/**
* Document Validation Error
*
* @api private
* @param {Document} instance
* @inherits MongooseError
*/
function ValidationError (instance) {
if (instance && instance.constructor.name === 'model') {
MongooseError.call(this, instance.constructor.modelName + " validation failed");
} else {
MongooseError.call(this, "Validation failed");
}
this.stack = new Error().stack;
this.name = 'ValidationError';
this.errors = {};
if (instance) {
instance.errors = this.errors;
}
}
/*!
* Inherits from MongooseError.
*/
ValidationError.prototype = Object.create(MongooseError.prototype);
ValidationError.prototype.constructor = MongooseError;
/**
* Console.log helper
*/
ValidationError.prototype.toString = function () {
var ret = this.name + ': ';
var msgs = [];
Object.keys(this.errors).forEach(function (key) {
if (this == this.errors[key]) return;
msgs.push(String(this.errors[key]));
}, this);
return ret + msgs.join(', ');
};
/*!
* Module exports
*/
module.exports = exports = ValidationError;

67
node_modules/mongoose/lib/error/validator.js generated vendored Normal file
View File

@@ -0,0 +1,67 @@
/*!
* Module dependencies.
*/
var MongooseError = require('../error.js');
var errorMessages = MongooseError.messages;
/**
* Schema validator error
*
* @param {Object} properties
* @inherits MongooseError
* @api private
*/
function ValidatorError (properties) {
var msg = properties.message;
if (!msg) {
msg = errorMessages.general.default;
}
this.properties = properties;
var message = this.formatMessage(msg, properties);
MongooseError.call(this, message);
this.stack = new Error().stack;
this.name = 'ValidatorError';
this.kind = properties.type;
this.path = properties.path;
this.value = properties.value;
};
/*!
* Inherits from MongooseError
*/
ValidatorError.prototype = Object.create(MongooseError.prototype);
ValidatorError.prototype.constructor = MongooseError;
/*!
* Formats error messages
*/
ValidatorError.prototype.formatMessage = function (msg, properties) {
var propertyNames = Object.keys(properties);
for (var i = 0; i < propertyNames.length; ++i) {
var propertyName = propertyNames[i];
if (propertyName === 'message') {
continue;
}
msg = msg.replace('{' + propertyName.toUpperCase() + '}', properties[propertyName]);
}
return msg;
};
/*!
* toString helper
*/
ValidatorError.prototype.toString = function () {
return this.message;
}
/*!
* exports
*/
module.exports = ValidatorError;

32
node_modules/mongoose/lib/error/version.js generated vendored Normal file
View File

@@ -0,0 +1,32 @@
/*!
* Module dependencies.
*/
var MongooseError = require('../error.js');
/**
* Version Error constructor.
*
* @inherits MongooseError
* @api private
*/
function VersionError () {
MongooseError.call(this, 'No matching document found.');
Error.captureStackTrace && Error.captureStackTrace(this, arguments.callee);
this.name = 'VersionError';
};
/*!
* Inherits from MongooseError.
*/
VersionError.prototype = Object.create(MongooseError.prototype);
VersionError.prototype.constructor = MongooseError;
/*!
* exports
*/
module.exports = VersionError;

655
node_modules/mongoose/lib/index.js generated vendored Normal file
View File

@@ -0,0 +1,655 @@
'use strict';
/*!
* Module dependencies.
*/
var Schema = require('./schema')
, SchemaType = require('./schematype')
, VirtualType = require('./virtualtype')
, STATES = require('./connectionstate')
, Types = require('./types')
, Query = require('./query')
, Promise = require('./promise')
, Model = require('./model')
, Document = require('./document')
, utils = require('./utils')
, format = utils.toCollectionName
, mongodb = require('mongodb')
, pkg = require('../package.json')
var querystring = require('querystring');
/**
* Mongoose constructor.
*
* The exports object of the `mongoose` module is an instance of this class.
* Most apps will only use this one instance.
*
* @api public
*/
function Mongoose () {
this.connections = [];
this.plugins = [];
this.models = {};
this.modelSchemas = {};
// default global options
this.options = {
pluralization: true
};
var conn = this.createConnection(); // default connection
conn.models = this.models;
};
/**
* Expose connection states for user-land
*
*/
Mongoose.prototype.STATES = STATES;
/**
* Sets mongoose options
*
* ####Example:
*
* mongoose.set('test', value) // sets the 'test' option to `value`
*
* mongoose.set('debug', true) // enable logging collection methods + arguments to the console
*
* @param {String} key
* @param {String} value
* @api public
*/
Mongoose.prototype.set = function (key, value) {
if (arguments.length == 1) {
return this.options[key];
}
this.options[key] = value;
return this;
};
/**
* Gets mongoose options
*
* ####Example:
*
* mongoose.get('test') // returns the 'test' value
*
* @param {String} key
* @method get
* @api public
*/
Mongoose.prototype.get = Mongoose.prototype.set;
/*!
* ReplSet connection string check.
*/
var rgxReplSet = /^.+,.+$/;
/**
* Checks if ?replicaSet query parameter is specified in URI
*
* ####Example:
*
* checkReplicaSetInUri('localhost:27000?replicaSet=rs0'); // true
*
* @param {String} uri
* @return {boolean}
* @api private
*/
var checkReplicaSetInUri = function(uri) {
if (!uri) {
return false;
}
var queryStringStart = uri.indexOf('?');
var isReplicaSet = false;
if (queryStringStart !== -1) {
try {
var obj = querystring.parse(uri.substr(queryStringStart + 1));
if (obj && obj.replicaSet) {
isReplicaSet = true;
}
} catch(e) {
return false;
}
}
return isReplicaSet;
};
/**
* Creates a Connection instance.
*
* Each `connection` instance maps to a single database. This method is helpful when mangaging multiple db connections.
*
* If arguments are passed, they are proxied to either [Connection#open](#connection_Connection-open) or [Connection#openSet](#connection_Connection-openSet) appropriately. This means we can pass `db`, `server`, and `replset` options to the driver. _Note that the `safe` option specified in your schema will overwrite the `safe` db option specified here unless you set your schemas `safe` option to `undefined`. See [this](/docs/guide.html#safe) for more information._
*
* _Options passed take precedence over options included in connection strings._
*
* ####Example:
*
* // with mongodb:// URI
* db = mongoose.createConnection('mongodb://user:pass@localhost:port/database');
*
* // and options
* var opts = { db: { native_parser: true }}
* db = mongoose.createConnection('mongodb://user:pass@localhost:port/database', opts);
*
* // replica sets
* db = mongoose.createConnection('mongodb://user:pass@localhost:port,anotherhost:port,yetanother:port/database');
*
* // and options
* var opts = { replset: { strategy: 'ping', rs_name: 'testSet' }}
* db = mongoose.createConnection('mongodb://user:pass@localhost:port,anotherhost:port,yetanother:port/database', opts);
*
* // with [host, database_name[, port] signature
* db = mongoose.createConnection('localhost', 'database', port)
*
* // and options
* var opts = { server: { auto_reconnect: false }, user: 'username', pass: 'mypassword' }
* db = mongoose.createConnection('localhost', 'database', port, opts)
*
* // initialize now, connect later
* db = mongoose.createConnection();
* db.open('localhost', 'database', port, [opts]);
*
* @param {String} [uri] a mongodb:// URI
* @param {Object} [options] options to pass to the driver
* @see Connection#open #connection_Connection-open
* @see Connection#openSet #connection_Connection-openSet
* @return {Connection} the created Connection object
* @api public
*/
Mongoose.prototype.createConnection = function () {
var conn = new Connection(this);
this.connections.push(conn);
if (arguments.length) {
if (rgxReplSet.test(arguments[0]) || checkReplicaSetInUri(arguments[0])) {
conn.openSet.apply(conn, arguments);
} else {
conn.open.apply(conn, arguments);
}
}
return conn;
};
/**
* Opens the default mongoose connection.
*
* If arguments are passed, they are proxied to either [Connection#open](#connection_Connection-open) or [Connection#openSet](#connection_Connection-openSet) appropriately.
*
* _Options passed take precedence over options included in connection strings._
*
* ####Example:
*
* mongoose.connect('mongodb://user:pass@localhost:port/database');
*
* // replica sets
* var uri = 'mongodb://user:pass@localhost:port/database,mongodb://anotherhost:port,mongodb://yetanother:port';
* mongoose.connect(uri);
*
* // with options
* mongoose.connect(uri, options);
*
* // connecting to multiple mongos
* var uri = 'mongodb://hostA:27501,hostB:27501';
* var opts = { mongos: true };
* mongoose.connect(uri, opts);
*
* @param {String} uri(s)
* @param {Object} [options]
* @param {Function} [callback]
* @see Mongoose#createConnection #index_Mongoose-createConnection
* @api public
* @return {Mongoose} this
*/
Mongoose.prototype.connect = function() {
var conn = this.connection;
if (rgxReplSet.test(arguments[0]) || checkReplicaSetInUri(arguments[0])) {
conn.openSet.apply(conn, arguments);
} else {
conn.open.apply(conn, arguments);
}
return this;
};
/**
* Disconnects all connections.
*
* @param {Function} [fn] called after all connection close.
* @return {Mongoose} this
* @api public
*/
Mongoose.prototype.disconnect = function (fn) {
var count = this.connections.length
, error
this.connections.forEach(function(conn){
conn.close(function(err){
if (error) return;
if (err) {
error = err;
if (fn) return fn(err);
throw err;
}
if (fn)
--count || fn();
});
});
return this;
};
/**
* Defines a model or retrieves it.
*
* Models defined on the `mongoose` instance are available to all connection created by the same `mongoose` instance.
*
* ####Example:
*
* var mongoose = require('mongoose');
*
* // define an Actor model with this mongoose instance
* mongoose.model('Actor', new Schema({ name: String }));
*
* // create a new connection
* var conn = mongoose.createConnection(..);
*
* // retrieve the Actor model
* var Actor = conn.model('Actor');
*
* _When no `collection` argument is passed, Mongoose produces a collection name by passing the model `name` to the [utils.toCollectionName](#utils_exports.toCollectionName) method. This method pluralizes the name. If you don't like this behavior, either pass a collection name or set your schemas collection name option._
*
* ####Example:
*
* var schema = new Schema({ name: String }, { collection: 'actor' });
*
* // or
*
* schema.set('collection', 'actor');
*
* // or
*
* var collectionName = 'actor'
* var M = mongoose.model('Actor', schema, collectionName)
*
* @param {String} name model name
* @param {Schema} [schema]
* @param {String} [collection] name (optional, induced from model name)
* @param {Boolean} [skipInit] whether to skip initialization (defaults to false)
* @api public
*/
Mongoose.prototype.model = function (name, schema, collection, skipInit) {
if ('string' == typeof schema) {
collection = schema;
schema = false;
}
if (utils.isObject(schema) && !(schema instanceof Schema)) {
schema = new Schema(schema);
}
if ('boolean' === typeof collection) {
skipInit = collection;
collection = null;
}
// handle internal options from connection.model()
var options;
if (skipInit && utils.isObject(skipInit)) {
options = skipInit;
skipInit = true;
} else {
options = {};
}
// look up schema for the collection.
if (!this.modelSchemas[name]) {
if (schema) {
// cache it so we only apply plugins once
this.modelSchemas[name] = schema;
this._applyPlugins(schema);
} else {
throw new mongoose.Error.MissingSchemaError(name);
}
}
var model;
var sub;
// connection.model() may be passing a different schema for
// an existing model name. in this case don't read from cache.
if (this.models[name] && false !== options.cache) {
if (schema instanceof Schema && schema != this.models[name].schema) {
throw new mongoose.Error.OverwriteModelError(name);
}
if (collection) {
// subclass current model with alternate collection
model = this.models[name];
schema = model.prototype.schema;
sub = model.__subclass(this.connection, schema, collection);
// do not cache the sub model
return sub;
}
return this.models[name];
}
// ensure a schema exists
if (!schema) {
schema = this.modelSchemas[name];
if (!schema) {
throw new mongoose.Error.MissingSchemaError(name);
}
}
// Apply relevant "global" options to the schema
if (!('pluralization' in schema.options)) schema.options.pluralization = this.options.pluralization;
if (!collection) {
collection = schema.get('collection') || format(name, schema.options);
}
var connection = options.connection || this.connection;
model = Model.compile(name, schema, collection, connection, this);
if (!skipInit) {
model.init();
}
if (false === options.cache) {
return model;
}
return this.models[name] = model;
}
/**
* Returns an array of model names created on this instance of Mongoose.
*
* ####Note:
*
* _Does not include names of models created using `connection.model()`._
*
* @api public
* @return {Array}
*/
Mongoose.prototype.modelNames = function () {
var names = Object.keys(this.models);
return names;
}
/**
* Applies global plugins to `schema`.
*
* @param {Schema} schema
* @api private
*/
Mongoose.prototype._applyPlugins = function (schema) {
for (var i = 0, l = this.plugins.length; i < l; i++) {
schema.plugin(this.plugins[i][0], this.plugins[i][1]);
}
}
/**
* Declares a global plugin executed on all Schemas.
*
* Equivalent to calling `.plugin(fn)` on each Schema you create.
*
* @param {Function} fn plugin callback
* @param {Object} [opts] optional options
* @return {Mongoose} this
* @see plugins ./plugins.html
* @api public
*/
Mongoose.prototype.plugin = function (fn, opts) {
this.plugins.push([fn, opts]);
return this;
};
/**
* The default connection of the mongoose module.
*
* ####Example:
*
* var mongoose = require('mongoose');
* mongoose.connect(...);
* mongoose.connection.on('error', cb);
*
* This is the connection used by default for every model created using [mongoose.model](#index_Mongoose-model).
*
* @property connection
* @return {Connection}
* @api public
*/
Mongoose.prototype.__defineGetter__('connection', function(){
return this.connections[0];
});
/*!
* Driver depentend APIs
*/
var driver = global.MONGOOSE_DRIVER_PATH || 'node-mongodb-native';
/*!
* Connection
*/
var Connection = require('./drivers/' + driver + '/connection');
/*!
* Collection
*/
var Collection = require('./drivers/' + driver + '/collection');
/**
* The Mongoose Collection constructor
*
* @method Collection
* @api public
*/
Mongoose.prototype.Collection = Collection;
/**
* The Mongoose [Connection](#connection_Connection) constructor
*
* @method Connection
* @api public
*/
Mongoose.prototype.Connection = Connection;
/**
* The Mongoose version
*
* @property version
* @api public
*/
Mongoose.prototype.version = pkg.version;
/**
* The Mongoose constructor
*
* The exports of the mongoose module is an instance of this class.
*
* ####Example:
*
* var mongoose = require('mongoose');
* var mongoose2 = new mongoose.Mongoose();
*
* @method Mongoose
* @api public
*/
Mongoose.prototype.Mongoose = Mongoose;
/**
* The Mongoose [Schema](#schema_Schema) constructor
*
* ####Example:
*
* var mongoose = require('mongoose');
* var Schema = mongoose.Schema;
* var CatSchema = new Schema(..);
*
* @method Schema
* @api public
*/
Mongoose.prototype.Schema = Schema;
/**
* The Mongoose [SchemaType](#schematype_SchemaType) constructor
*
* @method SchemaType
* @api public
*/
Mongoose.prototype.SchemaType = SchemaType;
/**
* The various Mongoose SchemaTypes.
*
* ####Note:
*
* _Alias of mongoose.Schema.Types for backwards compatibility._
*
* @property SchemaTypes
* @see Schema.SchemaTypes #schema_Schema.Types
* @api public
*/
Mongoose.prototype.SchemaTypes = Schema.Types;
/**
* The Mongoose [VirtualType](#virtualtype_VirtualType) constructor
*
* @method VirtualType
* @api public
*/
Mongoose.prototype.VirtualType = VirtualType;
/**
* The various Mongoose Types.
*
* ####Example:
*
* var mongoose = require('mongoose');
* var array = mongoose.Types.Array;
*
* ####Types:
*
* - [ObjectId](#types-objectid-js)
* - [Buffer](#types-buffer-js)
* - [SubDocument](#types-embedded-js)
* - [Array](#types-array-js)
* - [DocumentArray](#types-documentarray-js)
*
* Using this exposed access to the `ObjectId` type, we can construct ids on demand.
*
* var ObjectId = mongoose.Types.ObjectId;
* var id1 = new ObjectId;
*
* @property Types
* @api public
*/
Mongoose.prototype.Types = Types;
/**
* The Mongoose [Query](#query_Query) constructor.
*
* @method Query
* @api public
*/
Mongoose.prototype.Query = Query;
/**
* The Mongoose [Promise](#promise_Promise) constructor.
*
* @method Promise
* @api public
*/
Mongoose.prototype.Promise = Promise;
/**
* The Mongoose [Model](#model_Model) constructor.
*
* @method Model
* @api public
*/
Mongoose.prototype.Model = Model;
/**
* The Mongoose [Document](#document-js) constructor.
*
* @method Document
* @api public
*/
Mongoose.prototype.Document = Document;
/**
* The [MongooseError](#error_MongooseError) constructor.
*
* @method Error
* @api public
*/
Mongoose.prototype.Error = require('./error');
/**
* The [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) driver Mongoose uses.
*
* @property mongo
* @api public
*/
Mongoose.prototype.mongo = require('mongodb');
/**
* The [mquery](https://github.com/aheckmann/mquery) query builder Mongoose uses.
*
* @property mquery
* @api public
*/
Mongoose.prototype.mquery = require('mquery');
/*!
* The exports object is an instance of Mongoose.
*
* @api public
*/
var mongoose = module.exports = exports = new Mongoose;

31
node_modules/mongoose/lib/internal.js generated vendored Normal file
View File

@@ -0,0 +1,31 @@
/*!
* Dependencies
*/
var StateMachine = require('./statemachine')
var ActiveRoster = StateMachine.ctor('require', 'modify', 'init', 'default', 'ignore');
module.exports = exports = InternalCache;
function InternalCache () {
this.strictMode = undefined;
this.selected = undefined;
this.shardval = undefined;
this.saveError = undefined;
this.validationError = undefined;
this.adhocPaths = undefined;
this.removing = undefined;
this.inserting = undefined;
this.version = undefined;
this.getters = {};
this._id = undefined;
this.populate = undefined; // what we want to populate in this doc
this.populated = undefined;// the _ids that have been populated
this.wasPopulated = false; // if this doc was the result of a population
this.scope = undefined;
this.activePaths = new ActiveRoster;
// embedded docs
this.ownerDocument = undefined;
this.fullPath = undefined;
}

2854
node_modules/mongoose/lib/model.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

259
node_modules/mongoose/lib/promise.js generated vendored Normal file
View File

@@ -0,0 +1,259 @@
/*!
* Module dependencies
*/
var MPromise = require('mpromise');
var util = require('util');
/**
* Promise constructor.
*
* Promises are returned from executed queries. Example:
*
* var query = Candy.find({ bar: true });
* var promise = query.exec();
*
* @param {Function} fn a function which will be called when the promise is resolved that accepts `fn(err, ...){}` as signature
* @inherits mpromise https://github.com/aheckmann/mpromise
* @inherits NodeJS EventEmitter http://nodejs.org/api/events.html#events_class_events_eventemitter
* @event `err`: Emits when the promise is rejected
* @event `complete`: Emits when the promise is fulfilled
* @api public
*/
function Promise (fn) {
MPromise.call(this, fn);
}
/*!
* Inherit from mpromise
*/
Promise.prototype = Object.create(MPromise.prototype, {
constructor: {
value: Promise
, enumerable: false
, writable: true
, configurable: true
}
});
/*!
* Override event names for backward compatibility.
*/
Promise.SUCCESS = 'complete';
Promise.FAILURE = 'err';
/**
* Adds `listener` to the `event`.
*
* If `event` is either the success or failure event and the event has already been emitted, the`listener` is called immediately and passed the results of the original emitted event.
*
* @see mpromise#on https://github.com/aheckmann/mpromise#on
* @method on
* @memberOf Promise
* @param {String} event
* @param {Function} listener
* @return {Promise} this
* @api public
*/
/**
* Rejects this promise with `reason`.
*
* If the promise has already been fulfilled or rejected, not action is taken.
*
* @see mpromise#reject https://github.com/aheckmann/mpromise#reject
* @method reject
* @memberOf Promise
* @param {Object|String|Error} reason
* @return {Promise} this
* @api public
*/
/**
* Rejects this promise with `err`.
*
* If the promise has already been fulfilled or rejected, not action is taken.
*
* Differs from [#reject](#promise_Promise-reject) by first casting `err` to an `Error` if it is not `instanceof Error`.
*
* @api public
* @param {Error|String} err
* @return {Promise} this
*/
Promise.prototype.error = function (err) {
if (!(err instanceof Error)) {
if (err instanceof Object) {
err = util.inspect(err);
}
err = new Error(err);
}
return this.reject(err);
}
/**
* Resolves this promise to a rejected state if `err` is passed or a fulfilled state if no `err` is passed.
*
* If the promise has already been fulfilled or rejected, not action is taken.
*
* `err` will be cast to an Error if not already instanceof Error.
*
* _NOTE: overrides [mpromise#resolve](https://github.com/aheckmann/mpromise#resolve) to provide error casting._
*
* @param {Error} [err] error or null
* @param {Object} [val] value to fulfill the promise with
* @api public
*/
Promise.prototype.resolve = function (err) {
if (err) return this.error(err);
return this.fulfill.apply(this, Array.prototype.slice.call(arguments, 1));
};
/**
* Adds a single function as a listener to both err and complete.
*
* It will be executed with traditional node.js argument position when the promise is resolved.
*
* promise.addBack(function (err, args...) {
* if (err) return handleError(err);
* console.log('success');
* })
*
* Alias of [mpromise#onResolve](https://github.com/aheckmann/mpromise#onresolve).
*
* _Deprecated. Use `onResolve` instead._
*
* @method addBack
* @param {Function} listener
* @return {Promise} this
* @deprecated
*/
Promise.prototype.addBack = Promise.prototype.onResolve;
/**
* Fulfills this promise with passed arguments.
*
* @method fulfill
* @receiver Promise
* @see https://github.com/aheckmann/mpromise#fulfill
* @param {any} args
* @api public
*/
/**
* Fulfills this promise with passed arguments.
*
* Alias of [mpromise#fulfill](https://github.com/aheckmann/mpromise#fulfill).
*
* _Deprecated. Use `fulfill` instead._
*
* @method complete
* @receiver Promise
* @param {any} args
* @api public
* @deprecated
*/
Promise.prototype.complete = MPromise.prototype.fulfill;
/**
* Adds a listener to the `complete` (success) event.
*
* Alias of [mpromise#onFulfill](https://github.com/aheckmann/mpromise#onfulfill).
*
* _Deprecated. Use `onFulfill` instead._
*
* @method addCallback
* @param {Function} listener
* @return {Promise} this
* @api public
* @deprecated
*/
Promise.prototype.addCallback = Promise.prototype.onFulfill;
/**
* Adds a listener to the `err` (rejected) event.
*
* Alias of [mpromise#onReject](https://github.com/aheckmann/mpromise#onreject).
*
* _Deprecated. Use `onReject` instead._
*
* @method addErrback
* @param {Function} listener
* @return {Promise} this
* @api public
* @deprecated
*/
Promise.prototype.addErrback = Promise.prototype.onReject;
/**
* Creates a new promise and returns it. If `onFulfill` or `onReject` are passed, they are added as SUCCESS/ERROR callbacks to this promise after the nextTick.
*
* Conforms to [promises/A+](https://github.com/promises-aplus/promises-spec) specification.
*
* ####Example:
*
* var promise = Meetups.find({ tags: 'javascript' }).select('_id').exec();
* promise.then(function (meetups) {
* var ids = meetups.map(function (m) {
* return m._id;
* });
* return People.find({ meetups: { $in: ids }).exec();
* }).then(function (people) {
* if (people.length < 10000) {
* throw new Error('Too few people!!!');
* } else {
* throw new Error('Still need more people!!!');
* }
* }).then(null, function (err) {
* assert.ok(err instanceof Error);
* });
*
* @see promises-A+ https://github.com/promises-aplus/promises-spec
* @see mpromise#then https://github.com/aheckmann/mpromise#then
* @method then
* @memberOf Promise
* @param {Function} onFulFill
* @param {Function} onReject
* @return {Promise} newPromise
*/
/**
* Signifies that this promise was the last in a chain of `then()s`: if a handler passed to the call to `then` which produced this promise throws, the exception will go uncaught.
*
* ####Example:
*
* var p = new Promise;
* p.then(function(){ throw new Error('shucks') });
* setTimeout(function () {
* p.fulfill();
* // error was caught and swallowed by the promise returned from
* // p.then(). we either have to always register handlers on
* // the returned promises or we can do the following...
* }, 10);
*
* // this time we use .end() which prevents catching thrown errors
* var p = new Promise;
* var p2 = p.then(function(){ throw new Error('shucks') }).end(); // <--
* setTimeout(function () {
* p.fulfill(); // throws "shucks"
* }, 10);
*
* @api public
* @see mpromise#end https://github.com/aheckmann/mpromise#end
* @method end
* @memberOf Promise
*/
/*!
* expose
*/
module.exports = Promise;

2961
node_modules/mongoose/lib/query.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

79
node_modules/mongoose/lib/queryhelpers.js generated vendored Normal file
View File

@@ -0,0 +1,79 @@
/*!
* Module dependencies
*/
var utils = require('./utils')
/*!
* Prepare a set of path options for query population.
*
* @param {Query} query
* @param {Object} options
* @return {Array}
*/
exports.preparePopulationOptions = function preparePopulationOptions (query, options) {
var pop = utils.object.vals(query.options.populate);
// lean options should trickle through all queries
if (options.lean) pop.forEach(makeLean);
return pop;
}
/*!
* Prepare a set of path options for query population. This is the MongooseQuery
* version
*
* @param {Query} query
* @param {Object} options
* @return {Array}
*/
exports.preparePopulationOptionsMQ = function preparePopulationOptionsMQ (query, options) {
var pop = utils.object.vals(query._mongooseOptions.populate);
// lean options should trickle through all queries
if (options.lean) pop.forEach(makeLean);
return pop;
}
/*!
* If the document is a mapped discriminator type, it returns a model instance for that type, otherwise,
* it returns an instance of the given model.
*
* @param {Model} model
* @param {Object} doc
* @param {Object} fields
*
* @return {Model}
*/
exports.createModel = function createModel(model, doc, fields) {
var discriminatorMapping = model.schema
? model.schema.discriminatorMapping
: null;
var key = discriminatorMapping && discriminatorMapping.isRoot
? discriminatorMapping.key
: null;
if (key && doc[key] && model.discriminators && model.discriminators[doc[key]]) {
return new model.discriminators[doc[key]](undefined, fields, true);
}
return new model(undefined, fields, true);
}
/*!
* Set each path query option to lean
*
* @param {Object} option
*/
function makeLean (option) {
option.options || (option.options = {});
option.options.lean = true;
}

340
node_modules/mongoose/lib/querystream.js generated vendored Normal file
View File

@@ -0,0 +1,340 @@
/*!
* Module dependencies.
*/
var Stream = require('stream').Stream
var utils = require('./utils')
var helpers = require('./queryhelpers')
var K = function(k){ return k }
/**
* Provides a Node.js 0.8 style [ReadStream](http://nodejs.org/docs/v0.8.21/api/stream.html#stream_readable_stream) interface for Queries.
*
* var stream = Model.find().stream();
*
* stream.on('data', function (doc) {
* // do something with the mongoose document
* }).on('error', function (err) {
* // handle the error
* }).on('close', function () {
* // the stream is closed
* });
*
*
* The stream interface allows us to simply "plug-in" to other _Node.js 0.8_ style write streams.
*
* Model.where('created').gte(twoWeeksAgo).stream().pipe(writeStream);
*
* ####Valid options
*
* - `transform`: optional function which accepts a mongoose document. The return value of the function will be emitted on `data`.
*
* ####Example
*
* // JSON.stringify all documents before emitting
* var stream = Thing.find().stream({ transform: JSON.stringify });
* stream.pipe(writeStream);
*
* _NOTE: plugging into an HTTP response will *not* work out of the box. Those streams expect only strings or buffers to be emitted, so first formatting our documents as strings/buffers is necessary._
*
* _NOTE: these streams are Node.js 0.8 style read streams which differ from Node.js 0.10 style. Node.js 0.10 streams are not well tested yet and are not guaranteed to work._
*
* @param {Query} query
* @param {Object} [options]
* @inherits NodeJS Stream http://nodejs.org/docs/v0.8.21/api/stream.html#stream_readable_stream
* @event `data`: emits a single Mongoose document
* @event `error`: emits when an error occurs during streaming. This will emit _before_ the `close` event.
* @event `close`: emits when the stream reaches the end of the cursor or an error occurs, or the stream is manually `destroy`ed. After this event, no more events are emitted.
* @api public
*/
function QueryStream (query, options) {
Stream.call(this);
this.query = query;
this.readable = true;
this.paused = false;
this._cursor = null;
this._destroyed = null;
this._fields = null;
this._buffer = null;
this._inline = T_INIT;
this._running = false;
this._transform = options && 'function' == typeof options.transform
? options.transform
: K;
// give time to hook up events
var self = this;
process.nextTick(function () {
self._init();
});
}
/*!
* Inherit from Stream
*/
QueryStream.prototype.__proto__ = Stream.prototype;
/**
* Flag stating whether or not this stream is readable.
*
* @property readable
* @api public
*/
QueryStream.prototype.readable;
/**
* Flag stating whether or not this stream is paused.
*
* @property paused
* @api public
*/
QueryStream.prototype.paused;
// trampoline flags
var T_INIT = 0;
var T_IDLE = 1;
var T_CONT = 2;
/**
* Initializes the query.
*
* @api private
*/
QueryStream.prototype._init = function () {
if (this._destroyed) return;
var query = this.query
, model = query.model
, options = query._optionsForExec(model)
, self = this
try {
query.cast(model);
} catch (err) {
return self.destroy(err);
}
self._fields = utils.clone(query._fields);
options.fields = query._castFields(self._fields);
model.collection.find(query._conditions, options, function (err, cursor) {
if (err) return self.destroy(err);
self._cursor = cursor;
self._next();
});
}
/**
* Trampoline for pulling the next doc from cursor.
*
* @see QueryStream#__next #querystream_QueryStream-__next
* @api private
*/
QueryStream.prototype._next = function _next () {
if (this.paused || this._destroyed) {
return this._running = false;
}
this._running = true;
if (this._buffer && this._buffer.length) {
var arg;
while (!this.paused && !this._destroyed && (arg = this._buffer.shift())) {
this._onNextObject.apply(this, arg);
}
}
// avoid stack overflows with large result sets.
// trampoline instead of recursion.
while (this.__next()) {}
}
/**
* Pulls the next doc from the cursor.
*
* @see QueryStream#_next #querystream_QueryStream-_next
* @api private
*/
QueryStream.prototype.__next = function () {
if (this.paused || this._destroyed)
return this._running = false;
var self = this;
self._inline = T_INIT;
self._cursor.nextObject(function cursorcb (err, doc) {
self._onNextObject(err, doc);
});
// if onNextObject() was already called in this tick
// return ourselves to the trampoline.
if (T_CONT === this._inline) {
return true;
} else {
// onNextObject() hasn't fired yet. tell onNextObject
// that its ok to call _next b/c we are not within
// the trampoline anymore.
this._inline = T_IDLE;
}
}
/**
* Transforms raw `doc`s returned from the cursor into a model instance.
*
* @param {Error|null} err
* @param {Object} doc
* @api private
*/
QueryStream.prototype._onNextObject = function _onNextObject (err, doc) {
if (this._destroyed) return;
if (this.paused) {
this._buffer || (this._buffer = []);
this._buffer.push([err, doc]);
return this._running = false;
}
if (err) return this.destroy(err);
// when doc is null we hit the end of the cursor
if (!doc) {
this.emit('end');
return this.destroy();
}
var opts = this.query._mongooseOptions;
if (!opts.populate) {
return true === opts.lean ?
emit(this, doc) :
createAndEmit(this, null, doc);
}
var self = this;
var pop = helpers.preparePopulationOptionsMQ(self.query, self.query._mongooseOptions);
self.query.model.populate(doc, pop, function (err, doc) {
if (err) return self.destroy(err);
return true === opts.lean ?
emit(self, doc) :
createAndEmit(self, pop, doc);
});
}
function createAndEmit (self, populatedIds, doc) {
var instance = helpers.createModel(self.query.model, doc, self._fields);
var opts = populatedIds ?
{ populated: populatedIds } :
undefined;
instance.init(doc, opts, function (err) {
if (err) return self.destroy(err);
emit(self, instance);
});
}
/*!
* Emit a data event and manage the trampoline state
*/
function emit (self, doc) {
self.emit('data', self._transform(doc));
// trampoline management
if (T_IDLE === self._inline) {
// no longer in trampoline. restart it.
self._next();
} else {
// in a trampoline. tell __next that its
// ok to continue jumping.
self._inline = T_CONT;
}
}
/**
* Pauses this stream.
*
* @api public
*/
QueryStream.prototype.pause = function () {
this.paused = true;
}
/**
* Resumes this stream.
*
* @api public
*/
QueryStream.prototype.resume = function () {
this.paused = false;
if (!this._cursor) {
// cannot start if not initialized
return;
}
// are we within the trampoline?
if (T_INIT === this._inline) {
return;
}
if (!this._running) {
// outside QueryStream control, need manual restart
return this._next();
}
}
/**
* Destroys the stream, closing the underlying cursor. No more events will be emitted.
*
* @param {Error} [err]
* @api public
*/
QueryStream.prototype.destroy = function (err) {
if (this._destroyed) return;
this._destroyed = true;
this._running = false;
this.readable = false;
if (this._cursor) {
this._cursor.close();
}
if (err) {
this.emit('error', err);
}
this.emit('close');
}
/**
* Pipes this query stream into another stream. This method is inherited from NodeJS Streams.
*
* ####Example:
*
* query.stream().pipe(writeStream [, options])
*
* @method pipe
* @memberOf QueryStream
* @see NodeJS http://nodejs.org/api/stream.html
* @api public
*/
/*!
* Module exports
*/
module.exports = exports = QueryStream;

1042
node_modules/mongoose/lib/schema.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

397
node_modules/mongoose/lib/schema/array.js generated vendored Normal file
View File

@@ -0,0 +1,397 @@
/*!
* 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')
, cast = require('../cast')
, utils = require('../utils')
, isMongooseObject = utils.isMongooseObject
/**
* Array SchemaType constructor
*
* @param {String} key
* @param {SchemaType} cast
* @param {Object} options
* @inherits SchemaType
* @api private
*/
function SchemaArray (key, cast, options) {
if (cast) {
var castOptions = {};
if ('Object' === utils.getFunctionName(cast.constructor)) {
if (cast.type) {
// support { type: Woot }
castOptions = utils.clone(cast); // do not alter user arguments
delete castOptions.type;
cast = cast.type;
} else {
cast = Mixed;
}
}
// support { type: 'String' }
var name = 'string' == typeof cast
? cast
: utils.getFunctionName(cast);
var caster = name in Types
? Types[name]
: cast;
this.casterConstructor = caster;
this.caster = new caster(null, castOptions);
if (!(this.caster instanceof EmbeddedDoc)) {
this.caster.path = key;
}
}
SchemaType.call(this, key, options, 'Array');
var self = this
, defaultArr
, fn;
if (this.defaultValue) {
defaultArr = this.defaultValue;
fn = 'function' == typeof defaultArr;
}
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 = Object.create( SchemaType.prototype );
SchemaArray.prototype.constructor = SchemaArray;
/**
* Check required
*
* @param {Array} value
* @api private
*/
SchemaArray.prototype.checkRequired = function (value) {
return !!(value && value.length);
};
/**
* Overrides the getters application for the population special-case
*
* @param {Object} value
* @param {Object} scope
* @api private
*/
SchemaArray.prototype.applyGetters = function (value, scope) {
if (this.caster.options && this.caster.options.ref) {
// means the object id was populated
return value;
}
return SchemaType.prototype.applyGetters.call(this, value, scope);
};
/**
* Casts values for set().
*
* @param {Object} value
* @param {Document} doc document that triggers the casting
* @param {Boolean} init whether this is an initialization cast
* @api private
*/
SchemaArray.prototype.cast = function (value, doc, init) {
if (Array.isArray(value)) {
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++) {
value[i] = this.caster.cast(value[i], doc, init);
}
} catch (e) {
// rethrow
throw new CastError(e.type, value, this.path);
}
}
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 values for queries.
*
* @param {String} $conditional
* @param {any} [value]
* @api private
*/
SchemaArray.prototype.castForQuery = function ($conditional, value) {
var handler
, val;
if (arguments.length === 2) {
handler = this.$conditionalHandlers[$conditional];
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({ virtuals: false }) :
v;
});
} else if (method) {
val = method.call(caster, val);
}
}
return val && isMongooseObject(val) ?
val.toObject({ virtuals: false }) :
val;
};
/*!
* @ignore
*
* $atomic cast helpers
*/
function castToNumber (val) {
return Types.Number.prototype.cast.call(this, val);
}
function castArraysOfNumbers (arr, self) {
self || (self = this);
arr.forEach(function (v, i) {
if (Array.isArray(v)) {
castArraysOfNumbers(v, self);
} else {
arr[i] = castToNumber.call(self, v);
}
});
}
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) {
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) {
cast$geometry(val, this);
}
return 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];
}
return v;
}, this);
return this.castForQuery(val);
}
function cast$elemMatch (val) {
var hasDollarKey = false;
var keys = Object.keys(val);
var numKeys = keys.length;
var key;
var value;
for (var i = 0; i < numKeys; ++i) {
var key = keys[i];
var value = val[key];
if (key.indexOf('$') === 0 && value) {
val[key] = this.castForQuery(key, value);
hasDollarKey = true;
}
}
if (hasDollarKey) {
return val;
}
return cast(this.casterConstructor.schema, val);
}
function cast$geoIntersects (val) {
var geo = val.$geometry;
if (!geo) return;
cast$geometry(val, this);
return val;
}
var handle = SchemaArray.prototype.$conditionalHandlers = {};
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.
*/
module.exports = SchemaArray;

105
node_modules/mongoose/lib/schema/boolean.js generated vendored Normal file
View File

@@ -0,0 +1,105 @@
/*!
* Module dependencies.
*/
var utils = require('../utils');
var SchemaType = require('../schematype');
var utils = require('../utils');
/**
* Boolean SchemaType constructor.
*
* @param {String} path
* @param {Object} options
* @inherits SchemaType
* @api private
*/
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 = Object.create( SchemaType.prototype );
SchemaBoolean.prototype.constructor = SchemaBoolean;
/**
* Required validator
*
* @api private
*/
SchemaBoolean.prototype.checkRequired = function (value) {
return value === true || value === false;
};
/**
* Casts to boolean
*
* @param {Object} value
* @api private
*/
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;
}
/*!
* ignore
*/
function handleArray (val) {
var self = this;
return val.map(function (m) {
return self.cast(m);
});
}
SchemaBoolean.$conditionalHandlers =
utils.options(SchemaType.prototype.$conditionalHandlers, {
'$in': handleArray
});
/**
* Casts contents for queries.
*
* @param {String} $conditional
* @param {any} val
* @api private
*/
SchemaBoolean.prototype.castForQuery = function ($conditional, val) {
var handler;
if (2 === arguments.length) {
handler = SchemaBoolean.$conditionalHandlers[$conditional];
if (handler) {
return handler.call(this, val);
}
return this.cast(val);
}
return this.cast($conditional);
};
/*!
* Module exports.
*/
module.exports = SchemaBoolean;

183
node_modules/mongoose/lib/schema/buffer.js generated vendored Normal file
View File

@@ -0,0 +1,183 @@
/*!
* Module dependencies.
*/
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
*
* @param {String} key
* @param {SchemaType} cast
* @inherits SchemaType
* @api private
*/
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 = Object.create( SchemaType.prototype );
SchemaBuffer.prototype.constructor = SchemaBuffer;
/**
* Check required
*
* @api private
*/
SchemaBuffer.prototype.checkRequired = function (value, doc) {
if (SchemaType._isRef(this, value, doc, true)) {
return null != value;
} else {
return !!(value && value.length);
}
};
/**
* Casts contents
*
* @param {Object} value
* @param {Document} doc document that triggers the casting
* @param {Boolean} init
* @api private
*/
SchemaBuffer.prototype.cast = function (value, doc, init) {
if (SchemaType._isRef(this, value, doc, init)) {
// wait! we may need to cast this to a document
if (null == value) {
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)) {
return value;
} else if (!utils.isObject(value)) {
throw new CastError('buffer', value, this.path);
}
// Handle the case where user directly sets a populated
// path to a plain object; cast to the Model used in
// the population query.
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.$__.wasPopulated = true;
return ret;
}
// documents
if (value && value._id) {
value = value._id;
}
if (value && value.isMongooseBuffer) {
return value;
}
if (Buffer.isBuffer(value)) {
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]);
if (typeof value.sub_type !== 'number') {
throw new CastError('buffer', value, this.path);
}
ret._subtype = value.sub_type;
return ret;
}
if (null === value) return value;
var type = typeof value;
if ('string' == type || 'number' == type || Array.isArray(value)) {
var ret = new MongooseBuffer(value, [this.path, doc]);
return ret;
}
throw new CastError('buffer', value, this.path);
};
/*!
* ignore
*/
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,
'$in' : handleArray,
'$lt' : handleSingle,
'$lte': handleSingle,
'$ne' : handleSingle,
'$nin': handleArray
});
/**
* Casts contents for queries.
*
* @param {String} $conditional
* @param {any} [value]
* @api private
*/
SchemaBuffer.prototype.castForQuery = function ($conditional, val) {
var handler;
if (arguments.length === 2) {
handler = this.$conditionalHandlers[$conditional];
if (!handler)
throw new Error("Can't use " + $conditional + " with Buffer.");
return handler.call(this, val);
} else {
val = $conditional;
return this.cast(val).toObject();
}
};
/*!
* Module exports.
*/
module.exports = SchemaBuffer;

293
node_modules/mongoose/lib/schema/date.js generated vendored Normal file
View File

@@ -0,0 +1,293 @@
/*!
* Module requirements.
*/
var errorMessages = require('../error').messages
var utils = require('../utils');
var SchemaType = require('../schematype');
var CastError = SchemaType.CastError;
/**
* Date SchemaType constructor.
*
* @param {String} key
* @param {Object} options
* @inherits SchemaType
* @api private
*/
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 = Object.create( SchemaType.prototype );
SchemaDate.prototype.constructor = SchemaDate;
/**
* Declares a TTL index (rounded to the nearest second) for _Date_ types only.
*
* This sets the `expiresAfterSeconds` index option available in MongoDB >= 2.1.2.
* This index type is only compatible with Date types.
*
* ####Example:
*
* // expire in 24 hours
* new Schema({ createdAt: { type: Date, expires: 60*60*24 }});
*
* `expires` utilizes the `ms` module from [guille](https://github.com/guille/) allowing us to use a friendlier syntax:
*
* ####Example:
*
* // expire in 24 hours
* new Schema({ createdAt: { type: Date, expires: '24h' }});
*
* // expire in 1.5 hours
* new Schema({ createdAt: { type: Date, expires: '1.5h' }});
*
* // expire in 7 days
* var schema = new Schema({ createdAt: Date });
* schema.path('createdAt').expires('7d');
*
* @param {Number|String} when
* @added 3.0.0
* @return {SchemaType} this
* @api public
*/
SchemaDate.prototype.expires = function (when) {
if (!this._index || 'Object' !== this._index.constructor.name) {
this._index = {};
}
this._index.expires = when;
utils.expires(this._index);
return this;
};
/**
* Required validator for date
*
* @api private
*/
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'
});
}
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'
});
}
return this;
};
/**
* Casts to date
*
* @param {Object} value to cast
* @api private
*/
SchemaDate.prototype.cast = function (value) {
// If null or undefined
if (value == null || value === '')
return value;
if (value instanceof Date)
return value;
var date;
// support for timestamps
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());
}
if (date.toString() != 'Invalid Date') {
return date;
}
}
throw new CastError('date', value, this.path);
};
/*!
* Date Query casting.
*
* @api private
*/
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, {
'$all': handleArray,
'$gt': handleSingle,
'$gte': handleSingle,
'$in': handleArray,
'$lt': handleSingle,
'$lte': handleSingle,
'$ne': handleSingle,
'$nin': handleArray
});
/**
* Casts contents for queries.
*
* @param {String} $conditional
* @param {any} [value]
* @api private
*/
SchemaDate.prototype.castForQuery = function ($conditional, val) {
var handler;
if (2 !== arguments.length) {
return this.cast($conditional);
}
handler = this.$conditionalHandlers[$conditional];
if (!handler) {
throw new Error("Can't use " + $conditional + " with Date.");
}
return handler.call(this, val);
};
/*!
* Module exports.
*/
module.exports = SchemaDate;

249
node_modules/mongoose/lib/schema/documentarray.js generated vendored Normal file
View File

@@ -0,0 +1,249 @@
/*!
* Module dependencies.
*/
var ArrayType = require('./array');
var Document = require('../document');
var MongooseDocumentArray = require('../types/documentarray');
var SchemaType = require('../schematype');
var Subdocument = require('../types/embedded');
/**
* SubdocsArray SchemaType constructor
*
* @param {String} key
* @param {Schema} schema
* @param {Object} options
* @inherits SchemaArray
* @api private
*/
function DocumentArray (key, schema, options) {
// compile an embedded document for this schema
function EmbeddedDocument () {
Subdocument.apply(this, arguments);
}
EmbeddedDocument.prototype = Object.create(Subdocument.prototype);
EmbeddedDocument.prototype.$__setSchema(schema);
EmbeddedDocument.schema = schema;
// apply methods
for (var i in schema.methods)
EmbeddedDocument.prototype[i] = schema.methods[i];
// apply statics
for (var i in schema.statics)
EmbeddedDocument[i] = schema.statics[i];
EmbeddedDocument.options = options;
this.schema = schema;
ArrayType.call(this, key, EmbeddedDocument, options);
this.schema = schema;
var path = this.path;
var fn = this.defaultValue;
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 = Object.create( ArrayType.prototype );
DocumentArray.prototype.constructor = DocumentArray;
/**
* Performs local validations first, then validations on each embedded doc
*
* @api private
*/
DocumentArray.prototype.doValidate = function (array, fn, scope) {
SchemaType.prototype.doValidate.call(this, array, function (err) {
if (err) {
return fn(err);
}
var count = array && array.length;
var error;
if (!count) return fn();
// 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) {
// sidestep sparse entries
var doc = array[i];
if (!doc) {
--count || fn(error);
continue;
}
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
*
* @param {Object} value
* @param {Document} document that triggers the casting
* @api private
*/
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 && 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;
while (i--) {
if (!(value[i] instanceof Subdocument) && value[i]) {
if (init) {
selected || (selected = scopePaths(this, doc.$__.selected, init));
subdoc = new this.casterConstructor(null, value, true, selected, i);
value[i] = subdoc.init(value[i]);
} else {
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, undefined, undefined, i);
// 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.
* Necessary for proper default application of subdocument values.
*
* @param {DocumentArray} array - the array to scope `fields` paths
* @param {Object|undefined} fields - the root fields selected in the query
* @param {Boolean|undefined} init - if we are being created part of a query result
*/
function scopePaths (array, fields, init) {
if (!(init && fields)) return undefined;
var path = array.path + '.'
, keys = Object.keys(fields)
, i = keys.length
, selected = {}
, hasKeys
, key
while (i--) {
key = keys[i];
if (0 === key.indexOf(path)) {
hasKeys || (hasKeys = true);
selected[key.substring(path.length)] = fields[key];
}
}
return hasKeys && selected || undefined;
}
/*!
* Module exports.
*/
module.exports = DocumentArray;

28
node_modules/mongoose/lib/schema/index.js generated vendored Normal file
View File

@@ -0,0 +1,28 @@
/*!
* Module exports.
*/
exports.String = require('./string');
exports.Number = require('./number');
exports.Boolean = require('./boolean');
exports.DocumentArray = require('./documentarray');
exports.Array = require('./array');
exports.Buffer = require('./buffer');
exports.Date = require('./date');
exports.ObjectId = require('./objectid');
exports.Mixed = require('./mixed');
// alias
exports.Oid = exports.ObjectId;
exports.Object = exports.Mixed;
exports.Bool = exports.Boolean;

91
node_modules/mongoose/lib/schema/mixed.js generated vendored Normal file
View File

@@ -0,0 +1,91 @@
/*!
* Module dependencies.
*/
var SchemaType = require('../schematype');
var utils = require('../utils');
/**
* Mixed SchemaType constructor.
*
* @param {String} path
* @param {Object} options
* @inherits SchemaType
* @api private
*/
function Mixed (path, options) {
if (options && options.default) {
var def = options.default;
if (Array.isArray(def) && 0 === def.length) {
// make sure empty array defaults are handled
options.default = Array;
} else if (!options.shared &&
utils.isObject(def) &&
0 === Object.keys(def).length) {
// prevent odd "shared" objects between documents
options.default = function () {
return {}
}
}
}
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 = Object.create( SchemaType.prototype );
Mixed.prototype.constructor = Mixed;
/**
* Required validator
*
* @api private
*/
Mixed.prototype.checkRequired = function (val) {
return (val !== undefined) && (val !== null);
};
/**
* Casts `val` for Mixed.
*
* _this is a no-op_
*
* @param {Object} value to cast
* @api private
*/
Mixed.prototype.cast = function (val) {
return val;
};
/**
* Casts contents for queries.
*
* @param {String} $cond
* @param {any} [val]
* @api private
*/
Mixed.prototype.castForQuery = function ($cond, val) {
if (arguments.length === 2) return val;
return $cond;
};
/*!
* Module exports.
*/
module.exports = Mixed;

273
node_modules/mongoose/lib/schema/number.js generated vendored Normal file
View File

@@ -0,0 +1,273 @@
/*!
* Module requirements.
*/
var SchemaType = require('../schematype')
, CastError = SchemaType.CastError
, errorMessages = require('../error').messages
, utils = require('../utils')
, Document
/**
* Number SchemaType constructor.
*
* @param {String} key
* @param {Object} options
* @inherits SchemaType
* @api private
*/
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 = Object.create( SchemaType.prototype );
SchemaNumber.prototype.constructor = SchemaNumber;
/**
* Required validator for number
*
* @api private
*/
SchemaNumber.prototype.checkRequired = function checkRequired (value, doc) {
if (SchemaType._isRef(this, value, doc, true)) {
return null != value;
} else {
return typeof value == 'number' || value instanceof Number;
}
};
/**
* Sets a minimum number validator.
*
* ####Example:
*
* var s = new Schema({ n: { type: Number, min: 10 })
* var M = db.model('M', s)
* var m = new M({ n: 9 })
* m.save(function (err) {
* console.error(err) // validator error
* m.n = 10;
* 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, message) {
if (this.minValidator) {
this.validators = this.validators.filter(function (v) {
return v.validator != this.minValidator;
}, this);
}
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'
});
}
return this;
};
/**
* Sets a maximum number validator.
*
* ####Example:
*
* var s = new Schema({ n: { type: Number, max: 10 })
* var M = db.model('M', s)
* var m = new M({ n: 11 })
* m.save(function (err) {
* console.error(err) // validator error
* m.n = 10;
* 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, message) {
if (this.maxValidator) {
this.validators = this.validators.filter(function(v){
return v.validator != this.maxValidator;
}, this);
}
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'
});
}
return this;
};
/**
* Casts to number
*
* @param {Object} value value to cast
* @param {Document} doc document that triggers the casting
* @param {Boolean} init
* @api private
*/
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 (null == value) {
return value;
}
// lazy load
Document || (Document = require('./../document'));
if (value instanceof Document) {
value.$__.wasPopulated = true;
return value;
}
// setting a populated path
if ('number' == typeof value) {
return value;
} else if (Buffer.isBuffer(value) || !utils.isObject(value)) {
throw new CastError('number', value, this.path);
}
// Handle the case where user directly sets a populated
// path to a plain object; cast to the Model used in
// the population query.
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.$__.wasPopulated = true;
return ret;
}
var val = value && value._id
? value._id // documents
: value;
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 ('number' == typeof val) return val;
if (val.toString && !Array.isArray(val) &&
val.toString() == Number(val)) {
return new Number(val)
}
}
throw new CastError('number', value, this.path);
};
/*!
* ignore
*/
function handleSingle (val) {
return this.cast(val)
}
function handleArray (val) {
var self = this;
return val.map(function (m) {
return self.cast(m)
});
}
SchemaNumber.prototype.$conditionalHandlers =
utils.options(SchemaType.prototype.$conditionalHandlers, {
'$all': handleArray,
'$gt' : handleSingle,
'$gte': handleSingle,
'$in' : handleArray,
'$lt' : handleSingle,
'$lte': handleSingle,
'$ne' : handleSingle,
'$mod': handleArray,
'$nin': handleArray
});
/**
* Casts contents for queries.
*
* @param {String} $conditional
* @param {any} [value]
* @api private
*/
SchemaNumber.prototype.castForQuery = function ($conditional, val) {
var handler;
if (arguments.length === 2) {
handler = this.$conditionalHandlers[$conditional];
if (!handler)
throw new Error("Can't use " + $conditional + " with Number.");
return handler.call(this, val);
} else {
val = this.cast($conditional);
return val == null ? val : val
}
};
/*!
* Module exports.
*/
module.exports = SchemaNumber;

203
node_modules/mongoose/lib/schema/objectid.js generated vendored Normal file
View File

@@ -0,0 +1,203 @@
/*!
* Module dependencies.
*/
var SchemaType = require('../schematype')
, CastError = SchemaType.CastError
, oid = require('../types/objectid')
, utils = require('../utils')
, Document
/**
* ObjectId SchemaType constructor.
*
* @param {String} key
* @param {Object} options
* @inherits SchemaType
* @api private
*/
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 = Object.create( SchemaType.prototype );
ObjectId.prototype.constructor = ObjectId;
/**
* Adds an auto-generated ObjectId default if turnOn is true.
* @param {Boolean} turnOn auto generated ObjectId defaults
* @api public
* @return {SchemaType} this
*/
ObjectId.prototype.auto = function (turnOn) {
if (turnOn) {
this.default(defaultId);
this.set(resetId)
}
return this;
};
/**
* Check required
*
* @api private
*/
ObjectId.prototype.checkRequired = function checkRequired (value, doc) {
if (SchemaType._isRef(this, value, doc, true)) {
return null != value;
} else {
return value instanceof oid;
}
};
/**
* Casts to ObjectId
*
* @param {Object} value
* @param {Object} doc
* @param {Boolean} init whether this is an initialization cast
* @api private
*/
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 (null == value) {
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 (Buffer.isBuffer(value) || !utils.isObject(value)) {
throw new CastError('ObjectId', value, this.path);
}
// Handle the case where user directly sets a populated
// path to a plain object; cast to the Model used in
// the population query.
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.$__.wasPopulated = true;
return ret;
}
// If null or undefined
if (value == null) return value;
if (value instanceof oid)
return value;
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 instanceof Function) {
try {
return oid.createFromHexString(value.toString());
} catch (err) {
throw new CastError('ObjectId', value, this.path);
}
}
throw new CastError('ObjectId', value, this.path);
};
/*!
* ignore
*/
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, {
'$all': handleArray,
'$gt': handleSingle,
'$gte': handleSingle,
'$in': handleArray,
'$lt': handleSingle,
'$lte': handleSingle,
'$ne': handleSingle,
'$nin': handleArray
});
/**
* Casts contents for queries.
*
* @param {String} $conditional
* @param {any} [val]
* @api private
*/
ObjectId.prototype.castForQuery = function ($conditional, val) {
var handler;
if (arguments.length === 2) {
handler = this.$conditionalHandlers[$conditional];
if (!handler)
throw new Error("Can't use " + $conditional + " with ObjectId.");
return handler.call(this, val);
} else {
return this.cast($conditional);
}
};
/*!
* ignore
*/
function defaultId () {
return new oid();
};
function resetId (v) {
this.$__._id = null;
return v;
}
/*!
* Module exports.
*/
module.exports = ObjectId;

480
node_modules/mongoose/lib/schema/string.js generated vendored Normal file
View File

@@ -0,0 +1,480 @@
/*!
* Module dependencies.
*/
var SchemaType = require('../schematype')
, CastError = SchemaType.CastError
, errorMessages = require('../error').messages
, utils = require('../utils')
, Document
/**
* String SchemaType constructor.
*
* @param {String} key
* @param {Object} options
* @inherits SchemaType
* @api private
*/
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 = Object.create( SchemaType.prototype );
SchemaString.prototype.constructor = SchemaString;
/**
* Adds an enum validator
*
* ####Example:
*
* var states = 'opening open closing closed'.split(' ')
* 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(String(err)) // ValidationError: `invalid` is not a valid enum value for path `state`.
* m.state = 'open'
* m.save(callback) // success
* })
*
* // 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 () {
if (this.enumValidator) {
this.validators = this.validators.filter(function(v) {
return v.validator != this.enumValidator;
}, this);
this.enumValidator = false;
}
if (undefined === arguments[0] || false === arguments[0]) {
return this;
}
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]));
}
}
var vals = this.enumValues;
this.enumValidator = function (v) {
return undefined === v || ~vals.indexOf(v);
};
this.validators.push({
validator: this.enumValidator,
message: errorMessage,
type: 'enum'
});
return this;
};
/**
* Adds a lowercase setter.
*
* ####Example:
*
* var s = new Schema({ email: { type: String, lowercase: true }})
* var M = db.model('M', s);
* var m = new M({ email: 'SomeEmail@example.COM' });
* console.log(m.email) // someemail@example.com
*
* @api public
* @return {SchemaType} this
*/
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;
});
};
/**
* Adds an uppercase setter.
*
* ####Example:
*
* var s = new Schema({ caps: { type: String, uppercase: true }})
* var M = db.model('M', s);
* var m = new M({ caps: 'an example' });
* console.log(m.caps) // AN EXAMPLE
*
* @api public
* @return {SchemaType} this
*/
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;
});
};
/**
* Adds a trim setter.
*
* The string value will be trimmed when set.
*
* ####Example:
*
* var s = new Schema({ name: { type: String, trim: true }})
* var M = db.model('M', s)
* var string = ' some name '
* console.log(string.length) // 11
* var m = new M({ name: string })
* console.log(m.name.length) // 9
*
* @api public
* @return {SchemaType} this
*/
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 invalid value
* var minlength = [10, 'The value of path `{PATH}` (`{VALUE}`) is shorter than the minimum length ({MINLENGTH}).'];
* var schema = new Schema({ postalCode: { type: String, minlength: minlength })
* var Address = mongoose.model('Address', schema);
* var address = new Address({ postalCode: '9512' });
* s.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'
});
}
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 invalid value
* var maxlength = [10, '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 (10).
* })
*
* @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'
});
}
return this;
};
/**
* Sets a regexp validator.
*
* Any value that does not pass `regExp`.test(val) will fail validation.
*
* ####Example:
*
* var s = new Schema({ name: { type: String, match: /^a/ }})
* var M = db.model('M', s)
* var 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'
* 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, message) {
// yes, we allow multiple match validators
var msg = message || errorMessages.String.match;
var matchValidator = function(v) {
var ret = ((null != v && '' !== v)
? regExp.test(v)
: true);
return ret;
};
this.validators.push({ validator: matchValidator, message: msg, type: 'regexp' });
return this;
};
/**
* Check required
*
* @param {String|null|undefined} value
* @api private
*/
SchemaString.prototype.checkRequired = function checkRequired (value, doc) {
if (SchemaType._isRef(this, value, doc, true)) {
return null != value;
} else {
return (value instanceof String || typeof value == 'string') && value.length;
}
};
/**
* Casts to String
*
* @api private
*/
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 (null == value) {
return value;
}
// lazy load
Document || (Document = require('./../document'));
if (value instanceof Document) {
value.$__.wasPopulated = true;
return value;
}
// setting a populated path
if ('string' == typeof value) {
return value;
} else if (Buffer.isBuffer(value) || !utils.isObject(value)) {
throw new CastError('string', value, this.path);
}
// Handle the case where user directly sets a populated
// path to a plain object; cast to the Model used in
// the population query.
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.$__.wasPopulated = true;
return ret;
}
// If null or undefined
if (value == null) {
return value;
}
if ('undefined' !== typeof value) {
// handle documents being passed
if (value._id && 'string' == typeof value._id) {
return value._id;
}
// 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);
};
/*!
* ignore
*/
function handleSingle (val) {
return this.castForQuery(val);
}
function handleArray (val) {
var self = this;
return val.map(function (m) {
return self.castForQuery(m);
});
}
SchemaString.prototype.$conditionalHandlers =
utils.options(SchemaType.prototype.$conditionalHandlers, {
'$all': handleArray,
'$gt' : handleSingle,
'$gte': handleSingle,
'$in' : handleArray,
'$lt' : handleSingle,
'$lte': handleSingle,
'$ne' : handleSingle,
'$nin': handleArray,
'$options': handleSingle,
'$regex': handleSingle
});
/**
* Casts contents for queries.
*
* @param {String} $conditional
* @param {any} [val]
* @api private
*/
SchemaString.prototype.castForQuery = function ($conditional, val) {
var handler;
if (arguments.length === 2) {
handler = this.$conditionalHandlers[$conditional];
if (!handler)
throw new Error("Can't use " + $conditional + " with String.");
return handler.call(this, val);
} else {
val = $conditional;
if (val instanceof RegExp) return val;
return this.cast(val);
}
};
/*!
* Module exports.
*/
module.exports = SchemaString;

800
node_modules/mongoose/lib/schematype.js generated vendored Normal file
View File

@@ -0,0 +1,800 @@
/*!
* Module dependencies.
*/
var utils = require('./utils');
var error = require('./error');
var errorMessages = error.messages;
var CastError = error.CastError;
var ValidatorError = error.ValidatorError;
/**
* SchemaType constructor
*
* @param {String} path
* @param {Object} [options]
* @param {String} [instance]
* @api public
*/
function SchemaType (path, options, instance) {
this.path = path;
this.instance = instance;
this.validators = [];
this.setters = [];
this.getters = [];
this.options = options;
this._index = null;
this.selected;
for (var i in options) if (this[i] && 'function' == typeof this[i]) {
// { unique: true, index: true }
if ('index' == i && this._index) continue;
var opts = Array.isArray(options[i])
? options[i]
: [options[i]];
this[i].apply(this, opts);
}
};
/**
* Sets a default value for this SchemaType.
*
* ####Example:
*
* var schema = new Schema({ n: { type: Number, default: 10 })
* var M = db.model('M', schema)
* var m = new M;
* console.log(m.n) // 10
*
* Defaults can be either `functions` which return the value to use as the default or the literal value itself. Either way, the value will be cast based on its schema type before being set during document creation.
*
* ####Example:
*
* // values are cast:
* var schema = new Schema({ aNumber: { type: Number, default: 4.815162342 }})
* var M = db.model('M', schema)
* var m = new M;
* console.log(m.aNumber) // 4.815162342
*
* // default unique objects for Mixed types:
* var schema = new Schema({ mixed: Schema.Types.Mixed });
* schema.path('mixed').default(function () {
* return {};
* });
*
* // if we don't use a function to return object literals for Mixed defaults,
* // each document will receive a reference to the same object literal creating
* // a "shared" object instance:
* var schema = new Schema({ mixed: Schema.Types.Mixed });
* schema.path('mixed').default({});
* var M = db.model('M', schema);
* var m1 = new M;
* m1.mixed.added = 1;
* console.log(m1.mixed); // { added: 1 }
* var m2 = new M;
* console.log(m2.mixed); // { added: 1 }
*
* @param {Function|any} val the default value
* @return {defaultValue}
* @api public
*/
SchemaType.prototype.default = function (val) {
if (1 === arguments.length) {
this.defaultValue = typeof val === 'function'
? val
: this.cast(val);
return this;
} else if (arguments.length > 1) {
this.defaultValue = utils.args(arguments);
}
return this.defaultValue;
};
/**
* Declares the index options for this schematype.
*
* ####Example:
*
* var s = new Schema({ name: { type: String, index: true })
* var s = new Schema({ loc: { type: [Number], index: 'hashed' })
* var s = new Schema({ loc: { type: [Number], index: '2d', sparse: true })
* var s = new Schema({ loc: { type: [Number], index: { type: '2dsphere', sparse: true }})
* var s = new Schema({ date: { type: Date, index: { unique: true, expires: '1d' }})
* Schema.path('my.path').index(true);
* Schema.path('my.date').index({ expires: 60 });
* Schema.path('my.path').index({ unique: true, sparse: true });
*
* ####NOTE:
*
* _Indexes are created in the background by default. Specify `background: false` to override._
*
* [Direction doesn't matter for single key indexes](http://www.mongodb.org/display/DOCS/Indexes#Indexes-CompoundKeysIndexes)
*
* @param {Object|Boolean|String} options
* @return {SchemaType} this
* @api public
*/
SchemaType.prototype.index = function (options) {
this._index = options;
utils.expires(this._index);
return this;
};
/**
* Declares an unique index.
*
* ####Example:
*
* var s = new Schema({ name: { type: String, unique: true })
* Schema.path('name').index({ unique: true });
*
* _NOTE: violating the constraint returns an `E11000` error from MongoDB when saving, not a Mongoose validation error._
*
* @param {Boolean} bool
* @return {SchemaType} this
* @api public
*/
SchemaType.prototype.unique = function (bool) {
if (null == this._index || 'boolean' == typeof this._index) {
this._index = {};
} else if ('string' == typeof this._index) {
this._index = { type: this._index };
}
this._index.unique = bool;
return this;
};
/**
* Declares a full text index.
*
* ###Example:
*
* var s = new Schema({name : {type: String, text : true })
* Schema.path('name').index({text : true});
* @param bool
* @return {SchemaType} this
* @api public
*/
SchemaType.prototype.text = function(bool) {
if (null == this._index || 'boolean' == typeof this._index) {
this._index = {};
} else if ('string' == typeof this._index) {
this._index = { type: this._index };
}
this._index.text = bool;
return this;
};
/**
* Declares a sparse index.
*
* ####Example:
*
* var s = new Schema({ name: { type: String, sparse: true })
* Schema.path('name').index({ sparse: true });
*
* @param {Boolean} bool
* @return {SchemaType} this
* @api public
*/
SchemaType.prototype.sparse = function (bool) {
if (null == this._index || 'boolean' == typeof this._index) {
this._index = {};
} else if ('string' == typeof this._index) {
this._index = { type: this._index };
}
this._index.sparse = bool;
return this;
};
/**
* Adds a setter to this schematype.
*
* ####Example:
*
* function capitalize (val) {
* if ('string' != typeof val) val = '';
* return val.charAt(0).toUpperCase() + val.substring(1);
* }
*
* // defining within the schema
* var s = new Schema({ name: { type: String, set: capitalize }})
*
* // or by retreiving its SchemaType
* var s = new Schema({ name: String })
* s.path('name').set(capitalize)
*
* Setters allow you to transform the data before it gets to the raw mongodb document and is set as a value on an actual key.
*
* Suppose you are implementing user registration for a website. Users provide an email and password, which gets saved to mongodb. The email is a string that you will want to normalize to lower case, in order to avoid one email having more than one account -- e.g., otherwise, avenue@q.com can be registered for 2 accounts via avenue@q.com and AvEnUe@Q.CoM.
*
* You can set up email lower case normalization easily via a Mongoose setter.
*
* function toLower (v) {
* return v.toLowerCase();
* }
*
* var UserSchema = new Schema({
* email: { type: String, set: toLower }
* })
*
* var User = db.model('User', UserSchema)
*
* var user = new User({email: 'AVENUE@Q.COM'})
* console.log(user.email); // 'avenue@q.com'
*
* // or
* var user = new User
* user.email = 'Avenue@Q.com'
* console.log(user.email) // 'avenue@q.com'
*
* As you can see above, setters allow you to transform the data before it gets to the raw mongodb document and is set as a value on an actual key.
*
* _NOTE: we could have also just used the built-in `lowercase: true` SchemaType option instead of defining our own function._
*
* new Schema({ email: { type: String, lowercase: true }})
*
* Setters are also passed a second argument, the schematype on which the setter was defined. This allows for tailored behavior based on options passed in the schema.
*
* function inspector (val, schematype) {
* if (schematype.options.required) {
* return schematype.path + ' is required';
* } else {
* return val;
* }
* }
*
* var VirusSchema = new Schema({
* name: { type: String, required: true, set: inspector },
* taxonomy: { type: String, set: inspector }
* })
*
* var Virus = db.model('Virus', VirusSchema);
* var v = new Virus({ name: 'Parvoviridae', taxonomy: 'Parvovirinae' });
*
* console.log(v.name); // name is required
* console.log(v.taxonomy); // Parvovirinae
*
* @param {Function} fn
* @return {SchemaType} this
* @api public
*/
SchemaType.prototype.set = function (fn) {
if ('function' != typeof fn)
throw new TypeError('A setter must be a function.');
this.setters.push(fn);
return this;
};
/**
* Adds a getter to this schematype.
*
* ####Example:
*
* function dob (val) {
* if (!val) return val;
* return (val.getMonth() + 1) + "/" + val.getDate() + "/" + val.getFullYear();
* }
*
* // defining within the schema
* var s = new Schema({ born: { type: Date, get: dob })
*
* // or by retreiving its SchemaType
* var s = new Schema({ born: Date })
* s.path('born').get(dob)
*
* Getters allow you to transform the representation of the data as it travels from the raw mongodb document to the value that you see.
*
* Suppose you are storing credit card numbers and you want to hide everything except the last 4 digits to the mongoose user. You can do so by defining a getter in the following way:
*
* function obfuscate (cc) {
* return '****-****-****-' + cc.slice(cc.length-4, cc.length);
* }
*
* var AccountSchema = new Schema({
* creditCardNumber: { type: String, get: obfuscate }
* });
*
* var Account = db.model('Account', AccountSchema);
*
* Account.findById(id, function (err, found) {
* console.log(found.creditCardNumber); // '****-****-****-1234'
* });
*
* Getters are also passed a second argument, the schematype on which the getter was defined. This allows for tailored behavior based on options passed in the schema.
*
* function inspector (val, schematype) {
* if (schematype.options.required) {
* return schematype.path + ' is required';
* } else {
* return schematype.path + ' is not';
* }
* }
*
* var VirusSchema = new Schema({
* name: { type: String, required: true, get: inspector },
* taxonomy: { type: String, get: inspector }
* })
*
* var Virus = db.model('Virus', VirusSchema);
*
* Virus.findById(id, function (err, virus) {
* console.log(virus.name); // name is required
* console.log(virus.taxonomy); // taxonomy is not
* })
*
* @param {Function} fn
* @return {SchemaType} this
* @api public
*/
SchemaType.prototype.get = function (fn) {
if ('function' != typeof fn)
throw new TypeError('A getter must be a function.');
this.getters.push(fn);
return this;
};
/**
* Adds validator(s) for this document path.
*
* Validators always receive the value to validate as their first argument and must return `Boolean`. Returning `false` means validation failed.
*
* The error message argument is optional. If not passed, the [default generic error message template](#error_messages_MongooseError-messages) will be used.
*
* ####Examples:
*
* // make sure every value is equal to "something"
* function validator (val) {
* return val == 'something';
* }
* new Schema({ name: { type: String, validate: validator }});
*
* // with a custom error message
*
* var custom = [validator, 'Uh oh, {PATH} does not equal "something".']
* new Schema({ name: { type: String, validate: custom }});
*
* // adding many validators at a time
*
* var many = [
* { validator: validator, msg: 'uh oh' }
* , { validator: anotherValidator, msg: 'failed' }
* ]
* new Schema({ name: { type: String, validate: many }});
*
* // or utilizing SchemaType methods directly:
*
* var schema = new Schema({ name: 'string' });
* schema.path('name').validate(validator, 'validation of `{PATH}` failed with value `{VALUE}`');
*
* ####Error message templates:
*
* From the examples above, you may have noticed that error messages support baseic templating. There are a few other template keywords besides `{PATH}` and `{VALUE}` too. To find out more, details are available [here](#error_messages_MongooseError-messages)
*
* ####Asynchronous validation:
*
* Passing a validator function that receives two arguments tells mongoose that the validator is an asynchronous validator. The first argument passed to the validator function is the value being validated. The second argument is a callback function that must called when you finish validating the value and passed either `true` or `false` to communicate either success or failure respectively.
*
* schema.path('name').validate(function (value, respond) {
* doStuff(value, function () {
* ...
* respond(false); // validation failed
* })
* }, '{PATH} failed validation.');
*
* You might use asynchronous validators to retreive other documents from the database to validate against or to meet other I/O bound validation needs.
*
* Validation occurs `pre('save')` or whenever you manually execute [document#validate](#document_Document-validate).
*
* If validation fails during `pre('save')` and no callback was passed to receive the error, an `error` event will be emitted on your Models associated db [connection](#connection_Connection), passing the validation error object along.
*
* var conn = mongoose.createConnection(..);
* conn.on('error', handleError);
*
* var Product = conn.model('Product', yourSchema);
* var dvd = new Product(..);
* dvd.save(); // emits error on the `conn` above
*
* If you desire handling these errors at the Model level, attach an `error` listener to your Model and the event will instead be emitted there.
*
* // registering an error listener on the Model lets us handle errors more locally
* Product.on('error', handleError);
*
* @param {RegExp|Function|Object} obj validator
* @param {String} [errorMsg] optional error message
* @param {String} [type] optional validator type
* @return {SchemaType} this
* @api public
*/
SchemaType.prototype.validate = function (obj, message, type) {
if ('function' == typeof obj || obj && 'RegExp' === utils.getFunctionName(obj.constructor)) {
var properties;
if (message instanceof Object && !type) {
properties = utils.clone(message);
if (!properties.message) {
properties.message = properties.msg;
}
properties.validator = obj;
properties.type = properties.type || 'user defined';
} else {
if (!message) message = errorMessages.general.default;
if (!type) type = 'user defined';
properties = { message: message, type: type, validator: obj };
}
this.validators.push(properties);
return this;
}
var i
, length
, arg;
for (i=0, length=arguments.length; i<length; i++) {
arg = arguments[i];
if (!(arg && 'Object' === utils.getFunctionName(arg.constructor))) {
var msg = 'Invalid validator. Received (' + typeof arg + ') '
+ arg
+ '. See http://mongoosejs.com/docs/api.html#schematype_SchemaType-validate';
throw new Error(msg);
}
this.validate(arg.validator, arg);
}
return this;
};
/**
* Adds a required validator to this schematype. The required validator is added
* to the front of the validators array using `unshift()`.
*
* ####Example:
*
* var s = new Schema({ born: { type: Date, required: true })
*
* // or with custom error message
*
* var s = new Schema({ born: { type: Date, required: '{PATH} is required!' })
*
* // or through the path API
*
* Schema.path('name').required(true);
*
* // with custom error messaging
*
* Schema.path('name').required(true, 'grrr :( ');
*
*
* @param {Boolean} required enable/disable the validator
* @param {String} [message] optional custom error message
* @return {SchemaType} this
* @see Customized Error Messages #error_messages_MongooseError-messages
* @api public
*/
SchemaType.prototype.required = function (required, message) {
if (false === required) {
this.validators = this.validators.filter(function (v) {
return v.validator != this.requiredValidator;
}, this);
this.isRequired = false;
return this;
}
var self = this;
this.isRequired = true;
this.requiredValidator = function (v) {
// in here, `this` refers to the validating document.
// no validation when this path wasn't selected in the query.
if ('isSelected' in this &&
!this.isSelected(self.path) &&
!this.isModified(self.path)) return true;
return (('function' === typeof required) && !required.apply(this)) ||
self.checkRequired(v, this);
}
if ('string' == typeof required) {
message = required;
required = undefined;
}
var msg = message || errorMessages.general.required;
this.validators.unshift({
validator: this.requiredValidator,
message: msg,
type: 'required'
});
return this;
};
/**
* Gets the default value
*
* @param {Object} scope the scope which callback are executed
* @param {Boolean} init
* @api private
*/
SchemaType.prototype.getDefault = function (scope, init) {
var ret = 'function' === typeof this.defaultValue
? this.defaultValue.call(scope)
: this.defaultValue;
if (null !== ret && undefined !== ret) {
return this.cast(ret, scope, init);
} else {
return ret;
}
};
/**
* Applies setters
*
* @param {Object} value
* @param {Object} scope
* @param {Boolean} init
* @api private
*/
SchemaType.prototype.applySetters = function (value, scope, init, priorVal) {
var v = value
, setters = this.setters
, len = setters.length
, caster = this.caster;
while (len--) {
v = setters[len].call(scope, v, this);
}
if (Array.isArray(v) && caster && caster.setters) {
var newVal = [];
for (var i = 0; i < v.length; i++) {
newVal.push(caster.applySetters(v[i], scope, init, priorVal));
}
v = newVal;
}
if (null === v || undefined === v) return v;
// do not cast until all setters are applied #665
v = this.cast(v, scope, init, priorVal);
return v;
};
/**
* Applies getters to a value
*
* @param {Object} value
* @param {Object} scope
* @api private
*/
SchemaType.prototype.applyGetters = function (value, scope) {
var v = value
, getters = this.getters
, len = getters.length;
if (!len) {
return v;
}
while (len--) {
v = getters[len].call(scope, v, this);
}
return v;
};
/**
* Sets default `select()` behavior for this path.
*
* Set to `true` if this path should always be included in the results, `false` if it should be excluded by default. This setting can be overridden at the query level.
*
* ####Example:
*
* T = db.model('T', new Schema({ x: { type: String, select: true }}));
* T.find(..); // field x will always be selected ..
* // .. unless overridden;
* T.find().select('-x').exec(callback);
*
* @param {Boolean} val
* @return {SchemaType} this
* @api public
*/
SchemaType.prototype.select = function select (val) {
this.selected = !! val;
return this;
};
/**
* Performs a validation of `value` using the validators declared for this SchemaType.
*
* @param {any} value
* @param {Function} callback
* @param {Object} scope
* @api private
*/
SchemaType.prototype.doValidate = function (value, fn, scope) {
var err = false
, path = this.path
, count = this.validators.length;
if (!count) return fn(null);
var validate = function(ok, validatorProperties) {
if (err) return;
if (ok === undefined || ok) {
--count || fn(null);
} else {
err = new ValidatorError(validatorProperties);
fn(err);
}
};
var self = this;
this.validators.forEach(function (v) {
if (err) {
return;
}
var validator = v.validator;
var validatorProperties = utils.clone(v);
validatorProperties.path = path;
validatorProperties.value = value;
if (validator instanceof RegExp) {
validate(validator.test(value), validatorProperties);
} else if ('function' === typeof validator) {
if (value === undefined && !self.isRequired) {
validate(true, validatorProperties);
return;
}
if (2 === validator.length) {
validator.call(scope, value, function (ok) {
validate(ok, validatorProperties);
});
} else {
validate(validator.call(scope, value), validatorProperties);
}
}
});
};
/**
* Performs a validation of `value` using the validators declared for this SchemaType.
*
* ####Note:
*
* This method ignores the asynchronous validators.
*
* @param {any} value
* @param {Object} scope
* @return {MongooseError|undefined}
* @api private
*/
SchemaType.prototype.doValidateSync = function (value, scope) {
var err = null
, path = this.path
, count = this.validators.length;
if (!count) return null;
var validate = function(ok, validatorProperties) {
if (err) return;
if (ok === undefined || ok) {
} else {
err = new ValidatorError(validatorProperties);
}
};
var self = this;
if (value === undefined && !self.isRequired) {
return null;
}
this.validators.forEach(function (v) {
if (err) {
return;
}
var validator = v.validator;
var validatorProperties = utils.clone(v);
validatorProperties.path = path;
validatorProperties.value = value;
if (validator instanceof RegExp) {
validate(validator.test(value), validatorProperties);
} else if ('function' === typeof validator) {
// if not async validators
if (2 !== validator.length) {
validate(validator.call(scope, value), validatorProperties);
}
}
});
return err;
};
/**
* Determines if value is a valid Reference.
*
* @param {SchemaType} self
* @param {Object} value
* @param {Document} doc
* @param {Boolean} init
* @return {Boolean}
* @api private
*/
SchemaType._isRef = function (self, value, doc, init) {
// fast path
var ref = init && self.options && self.options.ref;
if (!ref && doc && doc.$__fullPath) {
// checks for
// - this populated with adhoc model and no ref was set in schema OR
// - setting / pushing values after population
var path = doc.$__fullPath(self.path);
var owner = doc.ownerDocument ? doc.ownerDocument() : doc;
ref = owner.populated(path);
}
if (ref) {
if (null == value) return true;
if (!Buffer.isBuffer(value) && // buffers are objects too
'Binary' != value._bsontype // raw binary value from the db
&& utils.isObject(value) // might have deselected _id in population query
) {
return true;
}
}
return false;
};
/*!
* ignore
*/
function handleSingle(val) {
return this.cast(val);
}
// Default conditional handlers for all schema types
SchemaType.prototype.$conditionalHandlers = {
'$eq': handleSingle
};
/*!
* Module exports.
*/
module.exports = exports = SchemaType;
exports.CastError = CastError;
exports.ValidatorError = ValidatorError;

147
node_modules/mongoose/lib/services/updateValidators.js generated vendored Normal file
View File

@@ -0,0 +1,147 @@
/*!
* Module dependencies.
*/
var async = require('async');
var ValidationError = require('../error/validation.js');
var ObjectId = require('../types/objectid');
/**
* Applies validators and defaults to update and fineOneAndUpdate operations,
* specifically passing a null doc as `this` to validators and defaults
*
* @param {Query} query
* @param {Schema} schema
* @param {Object} castedDoc
* @param {Object} options
* @method runValidatorsOnUpdate
* @api private
*/
module.exports = function(query, schema, castedDoc, options) {
var keys = Object.keys(castedDoc || {});
var updatedKeys = {};
var updatedValues = {};
var numKeys = keys.length;
var hasDollarUpdate = false;
for (var i = 0; i < numKeys; ++i) {
if (keys[i].charAt(0) === '$') {
var flat = flatten(castedDoc[keys[i]]);
var paths = Object.keys(flat);
var numPaths = paths.length;
for (var j = 0; j < numPaths; ++j) {
if (keys[i] === '$set' || keys[i] === '$setOnInsert') {
updatedValues[paths[j]] = flat[paths[j]];
} else if (keys[i] === '$unset') {
updatedValues[paths[j]] = undefined;
}
updatedKeys[paths[j]] = true;
}
hasDollarUpdate = true;
}
}
if (!hasDollarUpdate) {
updatedValues = flatten(castedDoc);
updatedKeys = Object.keys(updatedValues);
}
if (options && options.upsert) {
paths = Object.keys(query._conditions);
numPaths = keys.length;
for (var i = 0; i < numPaths; ++i) {
if (typeof query._conditions[paths[i]] === 'object') {
var conditionKeys = Object.keys(query._conditions[paths[i]]);
var numConditionKeys = conditionKeys.length;
var hasDollarKey = false;
for (var j = 0; j < numConditionKeys; ++j) {
if (conditionKeys[j].charAt(0) === '$') {
hasDollarKey = true;
break;
}
}
if (hasDollarKey) {
continue;
}
}
updatedKeys[paths[i]] = true;
}
if (options.setDefaultsOnInsert) {
schema.eachPath(function(path, schemaType) {
if (path === '_id') {
// Ignore _id for now because it causes bugs in 2.4
return;
}
var def = schemaType.getDefault(null, true);
if (!updatedKeys[path] && typeof def !== 'undefined') {
castedDoc.$setOnInsert = castedDoc.$setOnInsert || {};
castedDoc.$setOnInsert[path] = def;
updatedValues[path] = def;
}
});
}
}
var updates = Object.keys(updatedValues);
var numUpdates = updates.length;
var validatorsToExecute = [];
var validationErrors = [];
for (var i = 0; i < numUpdates; ++i) {
(function(i) {
if (schema.path(updates[i])) {
validatorsToExecute.push(function(callback) {
schema.path(updates[i]).doValidate(
updatedValues[updates[i]],
function(err) {
if (err) {
validationErrors.push(err);
}
callback(null);
},
null);
});
}
})(i);
}
return function(callback) {
async.parallel(validatorsToExecute, function() {
if (validationErrors.length) {
var err = new ValidationError(null);
for (var i = 0; i < validationErrors.length; ++i) {
err.errors[validationErrors[i].path] = validationErrors[i];
}
return callback(err);
}
callback(null);
});
};
};
function flatten(update, path) {
var keys = Object.keys(update);
var numKeys = keys.length;
var result = {};
path = path ? path + '.' : '';
for (var i = 0; i < numKeys; ++i) {
var key = keys[i];
var val = update[key];
if (shouldFlatten(val)) {
var flat = flatten(val, path + key);
for (var k in flat) {
result[k] = flat[k];
}
} else {
result[path + key] = val;
}
}
return result;
}
function shouldFlatten(val) {
return val && typeof val === 'object' && !(val instanceof ObjectId);
}

179
node_modules/mongoose/lib/statemachine.js generated vendored Normal file
View File

@@ -0,0 +1,179 @@
/*!
* Module dependencies.
*/
var utils = require('./utils');
/*!
* StateMachine represents a minimal `interface` for the
* constructors it builds via StateMachine.ctor(...).
*
* @api private
*/
var StateMachine = module.exports = exports = function StateMachine () {
}
/*!
* StateMachine.ctor('state1', 'state2', ...)
* A factory method for subclassing StateMachine.
* The arguments are a list of states. For each state,
* the constructor's prototype gets state transition
* methods named after each state. These transition methods
* place their path argument into the given state.
*
* @param {String} state
* @param {String} [state]
* @return {Function} subclass constructor
* @private
*/
StateMachine.ctor = function () {
var states = utils.args(arguments);
var ctor = function () {
StateMachine.apply(this, arguments);
this.paths = {};
this.states = {};
this.stateNames = states;
var i = states.length
, state;
while (i--) {
state = states[i];
this.states[state] = {};
}
};
ctor.prototype = new StateMachine();
states.forEach(function (state) {
// Changes the `path`'s state to `state`.
ctor.prototype[state] = function (path) {
this._changeState(path, state);
}
});
return ctor;
};
/*!
* This function is wrapped by the state change functions:
*
* - `require(path)`
* - `modify(path)`
* - `init(path)`
*
* @api private
*/
StateMachine.prototype._changeState = function _changeState (path, nextState) {
var prevBucket = this.states[this.paths[path]];
if (prevBucket) delete prevBucket[path];
this.paths[path] = nextState;
this.states[nextState][path] = true;
}
/*!
* ignore
*/
StateMachine.prototype.clear = function clear (state) {
var keys = Object.keys(this.states[state])
, i = keys.length
, path
while (i--) {
path = keys[i];
delete this.states[state][path];
delete this.paths[path];
}
}
/*!
* Checks to see if at least one path is in the states passed in via `arguments`
* e.g., this.some('required', 'inited')
*
* @param {String} state that we want to check for.
* @private
*/
StateMachine.prototype.some = function some () {
var self = this;
var what = arguments.length ? arguments : this.stateNames;
return Array.prototype.some.call(what, function (state) {
return Object.keys(self.states[state]).length;
});
}
/*!
* This function builds the functions that get assigned to `forEach` and `map`,
* since both of those methods share a lot of the same logic.
*
* @param {String} iterMethod is either 'forEach' or 'map'
* @return {Function}
* @api private
*/
StateMachine.prototype._iter = function _iter (iterMethod) {
return function () {
var numArgs = arguments.length
, states = utils.args(arguments, 0, numArgs-1)
, callback = arguments[numArgs-1];
if (!states.length) states = this.stateNames;
var self = this;
var paths = states.reduce(function (paths, state) {
return paths.concat(Object.keys(self.states[state]));
}, []);
return paths[iterMethod](function (path, i, paths) {
return callback(path, i, paths);
});
};
}
/*!
* Iterates over the paths that belong to one of the parameter states.
*
* The function profile can look like:
* this.forEach(state1, fn); // iterates over all paths in state1
* this.forEach(state1, state2, fn); // iterates over all paths in state1 or state2
* this.forEach(fn); // iterates over all paths in all states
*
* @param {String} [state]
* @param {String} [state]
* @param {Function} callback
* @private
*/
StateMachine.prototype.forEach = function forEach () {
this.forEach = this._iter('forEach');
return this.forEach.apply(this, arguments);
}
/*!
* Maps over the paths that belong to one of the parameter states.
*
* The function profile can look like:
* this.forEach(state1, fn); // iterates over all paths in state1
* this.forEach(state1, state2, fn); // iterates over all paths in state1 or state2
* this.forEach(fn); // iterates over all paths in all states
*
* @param {String} [state]
* @param {String} [state]
* @param {Function} callback
* @return {Array}
* @private
*/
StateMachine.prototype.map = function map () {
this.map = this._iter('map');
return this.map.apply(this, arguments);
}

741
node_modules/mongoose/lib/types/array.js generated vendored Normal file
View File

@@ -0,0 +1,741 @@
/*!
* Module dependencies.
*/
var EmbeddedDocument = require('./embedded');
var Document = require('../document');
var ObjectId = require('./objectid');
var utils = require('../utils');
var isMongooseObject = utils.isMongooseObject;
/**
* Mongoose Array constructor.
*
* ####NOTE:
*
* _Values always have to be passed to the constructor to initialize, otherwise `MongooseArray#push` will mark the array as modified._
*
* @param {Array} values
* @param {String} path
* @param {Document} doc parent document
* @api private
* @inherits Array
* @see http://bit.ly/f6CnZU
*/
function MongooseArray (values, path, doc) {
var arr = [].concat(values);
utils.decorate( arr, MongooseArray.mixin );
arr.isMongooseArray = true;
arr._atomics = {};
arr.validators = [];
arr._path = path;
// Because doc comes from the context of another function, doc === global
// can happen if there was a null somewhere up the chain (see #3020)
// RB Jun 17, 2015 updated to check for presence of expected paths instead
// to make more proof against unusual node environments
if (doc && doc instanceof Document) {
arr._parent = doc;
arr._schema = doc.schema.path(path);
}
return arr;
}
MongooseArray.mixin = {
/**
* Stores a queue of atomic operations to perform
*
* @property _atomics
* @api private
*/
_atomics: undefined,
/**
* Parent owner document
*
* @property _parent
* @api private
* @receiver MongooseArray
*/
_parent: undefined,
/**
* Casts a member based on this arrays schema.
*
* @param {any} value
* @return value the casted value
* @method _cast
* @api private
* @receiver MongooseArray
*/
_cast: function (value) {
var owner = this._owner;
var populated = false;
var Model;
if (this._parent) {
// if a populated array, we must cast to the same model
// instance as specified in the original query.
if (!owner) {
owner = this._owner = this._parent.ownerDocument
? this._parent.ownerDocument()
: this._parent;
}
populated = owner.populated(this._path, true);
}
if (populated && null != value) {
// cast to the populated Models schema
Model = populated.options.model;
// only objects are permitted so we can safely assume that
// non-objects are to be interpreted as _id
if (Buffer.isBuffer(value) ||
value instanceof ObjectId || !utils.isObject(value)) {
value = { _id: value };
}
// gh-2399
// we should cast model only when it's not a discriminator
var isDisc = value.schema && value.schema.discriminatorMapping &&
value.schema.discriminatorMapping.key !== undefined;
if (!isDisc) {
value = new Model(value);
}
return this._schema.caster.cast(value, this._parent, true)
}
return this._schema.caster.cast(value, this._parent, false)
},
/**
* Marks this array as modified.
*
* If it bubbles up from an embedded document change, then it takes the following arguments (otherwise, takes 0 arguments)
*
* @param {EmbeddedDocument} embeddedDoc the embedded doc that invoked this method on the Array
* @param {String} embeddedPath the path which changed in the embeddedDoc
* @method _markModified
* @api private
* @receiver MongooseArray
*/
_markModified: function (elem, embeddedPath) {
var parent = this._parent
, dirtyPath;
if (parent) {
dirtyPath = this._path;
if (arguments.length) {
if (null != embeddedPath) {
// an embedded doc bubbled up the change
dirtyPath = dirtyPath + '.' + this.indexOf(elem) + '.' + embeddedPath;
} else {
// directly set an index
dirtyPath = dirtyPath + '.' + elem;
}
}
parent.markModified(dirtyPath);
}
return this;
},
/**
* Register an atomic operation with the parent.
*
* @param {Array} op operation
* @param {any} val
* @method _registerAtomic
* @api private
* @receiver MongooseArray
*/
_registerAtomic: function (op, val) {
if ('$set' == op) {
// $set takes precedence over all other ops.
// mark entire array modified.
this._atomics = { $set: val };
return this;
}
var atomics = this._atomics;
// reset pop/shift after save
if ('$pop' == op && !('$pop' in atomics)) {
var self = this;
this._parent.once('save', function () {
self._popped = self._shifted = null;
});
}
// check for impossible $atomic combos (Mongo denies more than one
// $atomic op on a single path
if (this._atomics.$set ||
Object.keys(atomics).length && !(op in atomics)) {
// a different op was previously registered.
// save the entire thing.
this._atomics = { $set: this };
return this;
}
if (op === '$pullAll' || op === '$pushAll' || op === '$addToSet') {
atomics[op] || (atomics[op] = []);
atomics[op] = atomics[op].concat(val);
} else if (op === '$pullDocs') {
var pullOp = atomics['$pull'] || (atomics['$pull'] = {})
, selector = pullOp['_id'] || (pullOp['_id'] = {'$in' : [] });
selector['$in'] = selector['$in'].concat(val);
} else {
atomics[op] = val;
}
return this;
},
/**
* Depopulates stored atomic operation values as necessary for direct insertion to MongoDB.
*
* If no atomics exist, we return all array values after conversion.
*
* @return {Array}
* @method $__getAtomics
* @memberOf MongooseArray
* @api private
*/
$__getAtomics: function () {
var ret = [];
var keys = Object.keys(this._atomics);
var i = keys.length;
if (0 === i) {
ret[0] = ['$set', this.toObject({ depopulate: 1, transform: false })];
return ret;
}
while (i--) {
var op = keys[i];
var val = this._atomics[op];
// the atomic values which are arrays are not MongooseArrays. we
// need to convert their elements as if they were MongooseArrays
// to handle populated arrays versus DocumentArrays properly.
if (isMongooseObject(val)) {
val = val.toObject({ depopulate: 1, transform: false });
} else if (Array.isArray(val)) {
val = this.toObject.call(val, { depopulate: 1, transform: false });
} else if (val.valueOf) {
val = val.valueOf();
}
if ('$addToSet' == op) {
val = { $each: val }
}
ret.push([op, val]);
}
return ret;
},
/**
* Returns the number of pending atomic operations to send to the db for this array.
*
* @api private
* @return {Number}
* @method hasAtomics
* @receiver MongooseArray
*/
hasAtomics: function hasAtomics () {
if (!(this._atomics && 'Object' === this._atomics.constructor.name)) {
return 0;
}
return Object.keys(this._atomics).length;
},
/**
* Internal helper for .map()
*
* @api private
* @return {Number}
* @method _mapCast
* @receiver MongooseArray
*/
_mapCast: function(val, index) {
return this._cast(val, this.length + index);
},
/**
* Wraps [`Array#push`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/push) with proper change tracking.
*
* @param {Object} [args...]
* @api public
* @method push
* @receiver MongooseArray
*/
push: function () {
var values = [].map.call(arguments, this._mapCast, this);
values = this._schema.applySetters(values, this._parent);
var ret = [].push.apply(this, values);
// $pushAll might be fibbed (could be $push). But it makes it easier to
// handle what could have been $push, $pushAll combos
this._registerAtomic('$pushAll', values);
this._markModified();
return ret;
},
/**
* Pushes items to the array non-atomically.
*
* ####NOTE:
*
* _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it._
*
* @param {any} [args...]
* @api public
* @method nonAtomicPush
* @receiver MongooseArray
*/
nonAtomicPush: function () {
var values = [].map.call(arguments, this._mapCast, this);
var ret = [].push.apply(this, values);
this._registerAtomic('$set', this);
this._markModified();
return ret;
},
/**
* Pops the array atomically at most one time per document `save()`.
*
* #### NOTE:
*
* _Calling this mulitple times on an array before saving sends the same command as calling it once._
* _This update is implemented using the MongoDB [$pop](http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pop) method which enforces this restriction._
*
* doc.array = [1,2,3];
*
* var popped = doc.array.$pop();
* console.log(popped); // 3
* console.log(doc.array); // [1,2]
*
* // no affect
* popped = doc.array.$pop();
* console.log(doc.array); // [1,2]
*
* doc.save(function (err) {
* if (err) return handleError(err);
*
* // we saved, now $pop works again
* popped = doc.array.$pop();
* console.log(popped); // 2
* console.log(doc.array); // [1]
* })
*
* @api public
* @method $pop
* @memberOf MongooseArray
* @see mongodb http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pop
* @method $pop
* @receiver MongooseArray
*/
$pop: function () {
this._registerAtomic('$pop', 1);
this._markModified();
// only allow popping once
if (this._popped) return;
this._popped = true;
return [].pop.call(this);
},
/**
* Wraps [`Array#pop`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/pop) with proper change tracking.
*
* ####Note:
*
* _marks the entire array as modified which will pass the entire thing to $set potentially overwritting any changes that happen between when you retrieved the object and when you save it._
*
* @see MongooseArray#$pop #types_array_MongooseArray-%24pop
* @api public
* @method pop
* @receiver MongooseArray
*/
pop: function () {
var ret = [].pop.call(this);
this._registerAtomic('$set', this);
this._markModified();
return ret;
},
/**
* Atomically shifts the array at most one time per document `save()`.
*
* ####NOTE:
*
* _Calling this mulitple times on an array before saving sends the same command as calling it once._
* _This update is implemented using the MongoDB [$pop](http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pop) method which enforces this restriction._
*
* doc.array = [1,2,3];
*
* var shifted = doc.array.$shift();
* console.log(shifted); // 1
* console.log(doc.array); // [2,3]
*
* // no affect
* shifted = doc.array.$shift();
* console.log(doc.array); // [2,3]
*
* doc.save(function (err) {
* if (err) return handleError(err);
*
* // we saved, now $shift works again
* shifted = doc.array.$shift();
* console.log(shifted ); // 2
* console.log(doc.array); // [3]
* })
*
* @api public
* @memberOf MongooseArray
* @method $shift
* @see mongodb http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pop
*/
$shift: function $shift () {
this._registerAtomic('$pop', -1);
this._markModified();
// only allow shifting once
if (this._shifted) return;
this._shifted = true;
return [].shift.call(this);
},
/**
* Wraps [`Array#shift`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/unshift) with proper change tracking.
*
* ####Example:
*
* doc.array = [2,3];
* var res = doc.array.shift();
* console.log(res) // 2
* console.log(doc.array) // [3]
*
* ####Note:
*
* _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it._
*
* @api public
* @method shift
* @receiver MongooseArray
*/
shift: function () {
var ret = [].shift.call(this);
this._registerAtomic('$set', this);
this._markModified();
return ret;
},
/**
* Pulls items from the array atomically.
*
* ####Examples:
*
* doc.array.pull(ObjectId)
* doc.array.pull({ _id: 'someId' })
* doc.array.pull(36)
* doc.array.pull('tag 1', 'tag 2')
*
* To remove a document from a subdocument array we may pass an object with a matching `_id`.
*
* doc.subdocs.push({ _id: 4815162342 })
* doc.subdocs.pull({ _id: 4815162342 }) // removed
*
* Or we may passing the _id directly and let mongoose take care of it.
*
* doc.subdocs.push({ _id: 4815162342 })
* doc.subdocs.pull(4815162342); // works
*
* @param {any} [args...]
* @see mongodb http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pull
* @api public
* @method pull
* @receiver MongooseArray
*/
pull: function () {
var values = [].map.call(arguments, this._cast, this)
, cur = this._parent.get(this._path)
, i = cur.length
, mem;
while (i--) {
mem = cur[i];
if (mem instanceof EmbeddedDocument) {
if (values.some(function (v) { return v.equals(mem); } )) {
[].splice.call(cur, i, 1);
}
} else if (~cur.indexOf.call(values, mem)) {
[].splice.call(cur, i, 1);
}
}
if (values[0] instanceof EmbeddedDocument) {
this._registerAtomic('$pullDocs', values.map( function (v) { return v._id; } ));
} else {
this._registerAtomic('$pullAll', values);
}
this._markModified();
return this;
},
/**
* Wraps [`Array#splice`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/splice) with proper change tracking and casting.
*
* ####Note:
*
* _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it._
*
* @api public
* @method splice
* @receiver MongooseArray
*/
splice: function splice () {
var ret, vals, i;
if (arguments.length) {
vals = [];
for (i = 0; i < arguments.length; ++i) {
vals[i] = i < 2
? arguments[i]
: this._cast(arguments[i], arguments[0] + (i - 2));
}
ret = [].splice.apply(this, vals);
this._registerAtomic('$set', this);
this._markModified();
}
return ret;
},
/**
* Wraps [`Array#unshift`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/unshift) with proper change tracking.
*
* ####Note:
*
* _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it._
*
* @api public
* @method unshift
* @receiver MongooseArray
*/
unshift: function () {
var values = [].map.call(arguments, this._cast, this);
values = this._schema.applySetters(values, this._parent);
[].unshift.apply(this, values);
this._registerAtomic('$set', this);
this._markModified();
return this.length;
},
/**
* Wraps [`Array#sort`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/sort) with proper change tracking.
*
* ####NOTE:
*
* _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it._
*
* @api public
* @method sort
* @receiver MongooseArray
*/
sort: function () {
var ret = [].sort.apply(this, arguments);
this._registerAtomic('$set', this);
this._markModified();
return ret;
},
/**
* Adds values to the array if not already present.
*
* ####Example:
*
* console.log(doc.array) // [2,3,4]
* var added = doc.array.addToSet(4,5);
* console.log(doc.array) // [2,3,4,5]
* console.log(added) // [5]
*
* @param {any} [args...]
* @return {Array} the values that were added
* @receiver MongooseArray
* @api public
* @method addToSet
*/
addToSet: function addToSet () {
var values = [].map.call(arguments, this._mapCast, this);
values = this._schema.applySetters(values, this._parent);
var added = [];
var type = values[0] instanceof EmbeddedDocument ? 'doc' :
values[0] instanceof Date ? 'date' :
'';
values.forEach(function (v) {
var found;
switch (type) {
case 'doc':
found = this.some(function(doc){ return doc.equals(v) });
break;
case 'date':
var val = +v;
found = this.some(function(d){ return +d === val });
break;
default:
found = ~this.indexOf(v);
}
if (!found) {
[].push.call(this, v);
this._registerAtomic('$addToSet', v);
this._markModified();
[].push.call(added, v);
}
}, this);
return added;
},
/**
* Sets the casted `val` at index `i` and marks the array modified.
*
* ####Example:
*
* // given documents based on the following
* var Doc = mongoose.model('Doc', new Schema({ array: [Number] }));
*
* var doc = new Doc({ array: [2,3,4] })
*
* console.log(doc.array) // [2,3,4]
*
* doc.array.set(1,"5");
* console.log(doc.array); // [2,5,4] // properly cast to number
* doc.save() // the change is saved
*
* // VS not using array#set
* doc.array[1] = "5";
* console.log(doc.array); // [2,"5",4] // no casting
* doc.save() // change is not saved
*
* @return {Array} this
* @api public
* @method set
* @receiver MongooseArray
*/
set: function set (i, val) {
var value = this._cast(val, i);
value = this._schema.caster instanceof EmbeddedDocument ?
value :
this._schema.caster.applySetters(val, this._parent)
;
this[i] = value;
this._markModified(i);
return this;
},
/**
* Returns a native js Array.
*
* @param {Object} options
* @return {Array}
* @api public
* @method toObject
* @receiver MongooseArray
*/
toObject: function (options) {
if (options && options.depopulate) {
return this.map(function (doc) {
return doc instanceof Document
? doc.toObject(options)
: doc
});
}
return this.slice();
},
/**
* Helper for console.log
*
* @api public
* @method inspect
* @receiver MongooseArray
*/
inspect: function () {
return JSON.stringify(this);
},
/**
* Return the index of `obj` or `-1` if not found.
*
* @param {Object} obj the item to look for
* @return {Number}
* @api public
* @method indexOf
* @receiver MongooseArray
*/
indexOf: function indexOf (obj) {
if (obj instanceof ObjectId) obj = obj.toString();
for (var i = 0, len = this.length; i < len; ++i) {
if (obj == this[i])
return i;
}
return -1;
}
};
/**
* Alias of [pull](#types_array_MongooseArray-pull)
*
* @see MongooseArray#pull #types_array_MongooseArray-pull
* @see mongodb http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pull
* @api public
* @memberOf MongooseArray
* @method remove
*/
MongooseArray.mixin.remove = MongooseArray.mixin.pull;
/*!
* Module exports.
*/
module.exports = exports = MongooseArray;

269
node_modules/mongoose/lib/types/buffer.js generated vendored Normal file
View File

@@ -0,0 +1,269 @@
/*!
* Module dependencies.
*/
var Binary = require('../drivers').Binary
, utils = require('../utils');
/**
* Mongoose Buffer constructor.
*
* Values always have to be passed to the constructor to initialize.
*
* @param {Buffer} value
* @param {String} encode
* @param {Number} offset
* @api private
* @inherits Buffer
* @see http://bit.ly/f6CnZU
*/
function MongooseBuffer (value, encode, offset) {
var length = arguments.length;
var val;
if (0 === length || null === arguments[0] || undefined === arguments[0]) {
val = 0;
} else {
val = value;
}
var encoding;
var path;
var doc;
if (Array.isArray(encode)) {
// internal casting
path = encode[0];
doc = encode[1];
} else {
encoding = encode;
}
var buf = new Buffer(val, encoding, offset);
utils.decorate( buf, MongooseBuffer.mixin );
buf.isMongooseBuffer = true;
// make sure these internal props don't show up in Object.keys()
Object.defineProperties(buf, {
validators: { value: [] }
, _path: { value: path }
, _parent: { value: doc }
});
if (doc && "string" === typeof path) {
Object.defineProperty(buf, '_schema', {
value: doc.schema.path(path)
});
}
buf._subtype = 0;
return buf;
}
/*!
* Inherit from Buffer.
*/
//MongooseBuffer.prototype = new Buffer(0);
MongooseBuffer.mixin = {
/**
* Parent owner document
*
* @api private
* @property _parent
* @receiver MongooseBuffer
*/
_parent: undefined,
/**
* Default subtype for the Binary representing this Buffer
*
* @api private
* @property _subtype
* @receiver MongooseBuffer
*/
_subtype: undefined,
/**
* Marks this buffer as modified.
*
* @api private
* @method _markModified
* @receiver MongooseBuffer
*/
_markModified: function () {
var parent = this._parent;
if (parent) {
parent.markModified(this._path);
}
return this;
},
/**
* Writes the buffer.
*
* @api public
* @method write
* @receiver MongooseBuffer
*/
write: function () {
var written = Buffer.prototype.write.apply(this, arguments);
if (written > 0) {
this._markModified();
}
return written;
},
/**
* Copies the buffer.
*
* ####Note:
*
* `Buffer#copy` does not mark `target` as modified so you must copy from a `MongooseBuffer` for it to work as expected. This is a work around since `copy` modifies the target, not this.
*
* @return {MongooseBuffer}
* @param {Buffer} target
* @method copy
* @receiver MongooseBuffer
*/
copy: function (target) {
var ret = Buffer.prototype.copy.apply(this, arguments);
if (target && target.isMongooseBuffer) {
target._markModified();
}
return ret;
}
};
/*!
* Compile other Buffer methods marking this buffer as modified.
*/
;(
// node < 0.5
'writeUInt8 writeUInt16 writeUInt32 writeInt8 writeInt16 writeInt32 ' +
'writeFloat writeDouble fill ' +
'utf8Write binaryWrite asciiWrite set ' +
// node >= 0.5
'writeUInt16LE writeUInt16BE writeUInt32LE writeUInt32BE ' +
'writeInt16LE writeInt16BE writeInt32LE writeInt32BE ' +
'writeFloatLE writeFloatBE writeDoubleLE writeDoubleBE'
).split(' ').forEach(function (method) {
if (!Buffer.prototype[method]) return;
MongooseBuffer.mixin[method] = new Function(
'var ret = Buffer.prototype.'+method+'.apply(this, arguments);' +
'this._markModified();' +
'return ret;'
)
});
/**
* Converts this buffer to its Binary type representation.
*
* ####SubTypes:
*
* var bson = require('bson')
* bson.BSON_BINARY_SUBTYPE_DEFAULT
* bson.BSON_BINARY_SUBTYPE_FUNCTION
* bson.BSON_BINARY_SUBTYPE_BYTE_ARRAY
* bson.BSON_BINARY_SUBTYPE_UUID
* bson.BSON_BINARY_SUBTYPE_MD5
* bson.BSON_BINARY_SUBTYPE_USER_DEFINED
*
* doc.buffer.toObject(bson.BSON_BINARY_SUBTYPE_USER_DEFINED);
*
* @see http://bsonspec.org/#/specification
* @param {Hex} [subtype]
* @return {Binary}
* @api public
* @method toObject
* @receiver MongooseBuffer
*/
MongooseBuffer.mixin.toObject = function (options) {
var subtype = 'number' == typeof options
? options
: (this._subtype || 0);
return new Binary(this, subtype);
};
/**
* Determines if this buffer is equals to `other` buffer
*
* @param {Buffer} other
* @return {Boolean}
* @method equals
* @receiver MongooseBuffer
*/
MongooseBuffer.mixin.equals = function (other) {
if (!Buffer.isBuffer(other)) {
return false;
}
if (this.length !== other.length) {
return false;
}
for (var i = 0; i < this.length; ++i) {
if (this[i] !== other[i]) return false;
}
return true;
};
/**
* Sets the subtype option and marks the buffer modified.
*
* ####SubTypes:
*
* var bson = require('bson')
* bson.BSON_BINARY_SUBTYPE_DEFAULT
* bson.BSON_BINARY_SUBTYPE_FUNCTION
* bson.BSON_BINARY_SUBTYPE_BYTE_ARRAY
* bson.BSON_BINARY_SUBTYPE_UUID
* bson.BSON_BINARY_SUBTYPE_MD5
* bson.BSON_BINARY_SUBTYPE_USER_DEFINED
*
* doc.buffer.subtype(bson.BSON_BINARY_SUBTYPE_UUID);
*
* @see http://bsonspec.org/#/specification
* @param {Hex} subtype
* @api public
* @method subtype
* @receiver MongooseBuffer
*/
MongooseBuffer.mixin.subtype = function (subtype) {
if ('number' != typeof subtype) {
throw new TypeError('Invalid subtype. Expected a number');
}
if (this._subtype != subtype) {
this._markModified();
}
this._subtype = subtype;
};
/*!
* Module exports.
*/
MongooseBuffer.Binary = Binary;
module.exports = MongooseBuffer;

222
node_modules/mongoose/lib/types/documentarray.js generated vendored Normal file
View File

@@ -0,0 +1,222 @@
/*!
* Module dependencies.
*/
var MongooseArray = require('./array')
, ObjectId = require('./objectid')
, ObjectIdSchema = require('../schema/objectid')
, utils = require('../utils')
, util = require('util')
, Document = require('../document')
/**
* DocumentArray constructor
*
* @param {Array} values
* @param {String} path the path to this array
* @param {Document} doc parent document
* @api private
* @return {MongooseDocumentArray}
* @inherits MongooseArray
* @see http://bit.ly/f6CnZU
*/
function MongooseDocumentArray (values, path, doc) {
var arr = [].concat(values);
// Values always have to be passed to the constructor to initialize, since
// otherwise MongooseArray#push will mark the array as modified to the parent.
utils.decorate( arr, MongooseDocumentArray.mixin );
arr.isMongooseArray = true;
arr.isMongooseDocumentArray = true;
arr._atomics = {};
arr.validators = [];
arr._path = path;
// Because doc comes from the context of another function, doc === global
// can happen if there was a null somewhere up the chain (see #3020 && #3034)
// RB Jun 17, 2015 updated to check for presence of expected paths instead
// to make more proof against unusual node environments
if (doc && doc instanceof Document) {
arr._parent = doc;
arr._schema = doc.schema.path(path);
arr._handlers = {
isNew: arr.notify('isNew'),
save: arr.notify('save')
};
doc.on('save', arr._handlers.save);
doc.on('isNew', arr._handlers.isNew);
}
return arr;
}
/*!
* Inherits from MongooseArray
*/
MongooseDocumentArray.mixin = Object.create( MongooseArray.mixin );
/**
* Overrides MongooseArray#cast
*
* @method _cast
* @api private
* @receiver MongooseDocumentArray
*/
MongooseDocumentArray.mixin._cast = function (value, index) {
if (value instanceof this._schema.casterConstructor) {
if (!(value.__parent && value.__parentArray)) {
// value may have been created using array.create()
value.__parent = this._parent;
value.__parentArray = this;
}
value.__index = index;
return value;
}
// handle cast('string') or cast(ObjectId) etc.
// only objects are permitted so we can safely assume that
// non-objects are to be interpreted as _id
if (Buffer.isBuffer(value) ||
value instanceof ObjectId || !utils.isObject(value)) {
value = { _id: value };
}
return new this._schema.casterConstructor(value, this, undefined, undefined, index);
};
/**
* Searches array items for the first document with a matching _id.
*
* ####Example:
*
* var embeddedDoc = m.array.id(some_id);
*
* @return {EmbeddedDocument|null} the subdocument or null if not found.
* @param {ObjectId|String|Number|Buffer} id
* @TODO cast to the _id based on schema for proper comparison
* @method id
* @api public
* @receiver MongooseDocumentArray
*/
MongooseDocumentArray.mixin.id = function (id) {
var casted
, sid
, _id
try {
var casted_ = ObjectIdSchema.prototype.cast.call({}, id);
if (casted_) casted = String(casted_);
} catch (e) {
casted = null;
}
for (var i = 0, l = this.length; i < l; i++) {
_id = this[i].get('_id');
if (_id instanceof Document) {
sid || (sid = String(id));
if (sid == _id._id) return this[i];
} else if (!(_id instanceof ObjectId)) {
sid || (sid = String(id));
if (sid == _id) return this[i];
} else if (casted == _id) {
return this[i];
}
}
return null;
};
/**
* Returns a native js Array of plain js objects
*
* ####NOTE:
*
* _Each sub-document is converted to a plain object by calling its `#toObject` method._
*
* @param {Object} [options] optional options to pass to each documents `toObject` method call during conversion
* @return {Array}
* @method toObject
* @api public
* @receiver MongooseDocumentArray
*/
MongooseDocumentArray.mixin.toObject = function (options) {
return this.map(function (doc) {
return doc && doc.toObject(options) || null;
});
};
/**
* Helper for console.log
*
* @method inspect
* @api public
* @receiver MongooseDocumentArray
*/
MongooseDocumentArray.mixin.inspect = function () {
return '[' + Array.prototype.map.call(this, function (doc) {
if (doc) {
return doc.inspect
? doc.inspect()
: util.inspect(doc)
}
return 'null'
}).join('\n') + ']';
};
/**
* Creates a subdocument casted to this schema.
*
* This is the same subdocument constructor used for casting.
*
* @param {Object} obj the value to cast to this arrays SubDocument schema
* @method create
* @api public
* @receiver MongooseDocumentArray
*/
MongooseDocumentArray.mixin.create = function (obj) {
return new this._schema.casterConstructor(obj);
}
/**
* Creates a fn that notifies all child docs of `event`.
*
* @param {String} event
* @return {Function}
* @method notify
* @api private
* @receiver MongooseDocumentArray
*/
MongooseDocumentArray.mixin.notify = function notify (event) {
var self = this;
return function notify (val) {
var i = self.length;
while (i--) {
if (!self[i]) continue;
switch(event) {
// only swap for save event for now, we may change this to all event types later
case 'save':
val = self[i];
break;
default:
// NO-OP
break;
}
self[i].emit(event, val);
}
}
}
/*!
* Module exports.
*/
module.exports = MongooseDocumentArray;

310
node_modules/mongoose/lib/types/embedded.js generated vendored Normal file
View File

@@ -0,0 +1,310 @@
/*!
* Module dependencies.
*/
var Document = require('../document_provider')();
var inspect = require('util').inspect;
var Promise = require('../promise');
/**
* EmbeddedDocument constructor.
*
* @param {Object} obj js object returned from the db
* @param {MongooseDocumentArray} parentArr the parent array of this document
* @param {Boolean} skipId
* @inherits Document
* @api private
*/
function EmbeddedDocument (obj, parentArr, skipId, fields, index) {
if (parentArr) {
this.__parentArray = parentArr;
this.__parent = parentArr._parent;
} else {
this.__parentArray = undefined;
this.__parent = undefined;
}
this.__index = index;
Document.call(this, obj, fields, skipId);
var self = this;
this.on('isNew', function (val) {
self.isNew = val;
});
}
/*!
* Inherit from Document
*/
EmbeddedDocument.prototype = Object.create( Document.prototype );
EmbeddedDocument.prototype.constructor = EmbeddedDocument;
/**
* Marks the embedded doc modified.
*
* ####Example:
*
* var doc = blogpost.comments.id(hexstring);
* doc.mixed.type = 'changed';
* doc.markModified('mixed.type');
*
* @param {String} path the path which changed
* @api public
* @receiver EmbeddedDocument
*/
EmbeddedDocument.prototype.markModified = function (path) {
if (!this.__parentArray) return;
this.$__.activePaths.modify(path);
if (this.isNew) {
// Mark the WHOLE parent array as modified
// if this is a new document (i.e., we are initializing
// a document),
this.__parentArray._markModified();
} else {
this.__parentArray._markModified(this, path);
}
};
/**
* Used as a stub for [hooks.js](https://github.com/bnoguchi/hooks-js/tree/31ec571cef0332e21121ee7157e0cf9728572cc3)
*
* ####NOTE:
*
* _This is a no-op. Does not actually save the doc to the db._
*
* @param {Function} [fn]
* @return {Promise} resolved Promise
* @api private
*/
EmbeddedDocument.prototype.save = function (fn) {
var promise = new Promise(fn);
promise.fulfill();
return promise;
}
/**
* Removes the subdocument from its parent array.
*
* @param {Function} [fn]
* @api public
*/
EmbeddedDocument.prototype.remove = function (fn) {
if (!this.__parentArray) return this;
var _id;
if (!this.willRemove) {
_id = this._doc._id;
if (!_id) {
throw new Error('For your own good, Mongoose does not know ' +
'how to remove an EmbeddedDocument that has no _id');
}
this.__parentArray.pull({ _id: _id });
this.willRemove = true;
registerRemoveListener(this);
}
if (fn)
fn(null);
return this;
};
/*!
* Registers remove event listeners for triggering
* on subdocuments.
*
* @param {EmbeddedDocument} sub
* @api private
*/
function registerRemoveListener (sub) {
var owner = sub.ownerDocument();
owner.on('save', emitRemove);
owner.on('remove', emitRemove);
function emitRemove () {
owner.removeListener('save', emitRemove);
owner.removeListener('remove', emitRemove);
sub.emit('remove', sub);
owner = sub = emitRemove = null;
};
};
/**
* Override #update method of parent documents.
* @api private
*/
EmbeddedDocument.prototype.update = function () {
throw new Error('The #update method is not available on EmbeddedDocuments');
}
/**
* Helper for console.log
*
* @api public
*/
EmbeddedDocument.prototype.inspect = function () {
return inspect(this.toObject());
};
/**
* Marks a path as invalid, causing validation to fail.
*
* @param {String} path the field to invalidate
* @param {String|Error} err error which states the reason `path` was invalid
* @return {Boolean}
* @api public
*/
EmbeddedDocument.prototype.invalidate = function (path, err, val, first) {
if (!this.__parent) {
var msg = 'Unable to invalidate a subdocument that has not been added to an array.'
throw new Error(msg);
}
var index = this.__index;
if (typeof index !== 'undefined') {
var parentPath = this.__parentArray._path;
var fullPath = [parentPath, index, path].join('.');
this.__parent.invalidate(fullPath, err, val);
}
if (first) {
this.$__.validationError = this.ownerDocument().$__.validationError;
}
return true;
};
/**
* Marks a path as valid, removing existing validation errors.
*
* @param {String} path the field to mark as valid
* @api private
* @method $markValid
* @receiver EmbeddedDocument
*/
EmbeddedDocument.prototype.$markValid = function(path) {
if (!this.__parent) {
return;
}
var index = this.__index;
if (typeof index !== 'undefined') {
var parentPath = this.__parentArray._path;
var fullPath = [parentPath, index, path].join('.');
this.__parent.$markValid(fullPath);
}
};
/**
* Checks if a path is invalid
*
* @param {String} path the field to check
* @api private
* @method $isValid
* @receiver EmbeddedDocument
*/
EmbeddedDocument.prototype.$isValid = function(path) {
var index = this.__index;
if (typeof index !== 'undefined') {
var parentPath = this.__parentArray._path;
var fullPath = [parentPath, index, path].join('.');
return !this.__parent.$__.validationError ||
!this.__parent.$__.validationError.errors[path];
}
return true;
};
/**
* Returns the top level document of this sub-document.
*
* @return {Document}
*/
EmbeddedDocument.prototype.ownerDocument = function () {
if (this.$__.ownerDocument) {
return this.$__.ownerDocument;
}
var parent = this.__parent;
if (!parent) return this;
while (parent.__parent) {
parent = parent.__parent;
}
return this.$__.ownerDocument = parent;
}
/**
* Returns the full path to this document. If optional `path` is passed, it is appended to the full path.
*
* @param {String} [path]
* @return {String}
* @api private
* @method $__fullPath
* @memberOf EmbeddedDocument
*/
EmbeddedDocument.prototype.$__fullPath = function (path) {
if (!this.$__.fullPath) {
var parent = this;
if (!parent.__parent) return path;
var paths = [];
while (parent.__parent) {
paths.unshift(parent.__parentArray._path);
parent = parent.__parent;
}
this.$__.fullPath = paths.join('.');
if (!this.$__.ownerDocument) {
// optimization
this.$__.ownerDocument = parent;
}
}
return path
? this.$__.fullPath + '.' + path
: this.$__.fullPath;
}
/**
* Returns this sub-documents parent document.
*
* @api public
*/
EmbeddedDocument.prototype.parent = function () {
return this.__parent;
}
/**
* Returns this sub-documents parent array.
*
* @api public
*/
EmbeddedDocument.prototype.parentArray = function () {
return this.__parentArray;
}
/*!
* Module exports.
*/
module.exports = EmbeddedDocument;

13
node_modules/mongoose/lib/types/index.js generated vendored Normal file
View File

@@ -0,0 +1,13 @@
/*!
* Module exports.
*/
exports.Array = require('./array');
exports.Buffer = require('./buffer');
exports.Document = // @deprecate
exports.Embedded = require('./embedded');
exports.DocumentArray = require('./documentarray');
exports.ObjectId = require('./objectid');

13
node_modules/mongoose/lib/types/objectid.js generated vendored Normal file
View File

@@ -0,0 +1,13 @@
/**
* ObjectId type constructor
*
* ####Example
*
* var id = new mongoose.Types.ObjectId;
*
* @constructor ObjectId
*/
var ObjectId = require('../drivers').ObjectId;
module.exports = ObjectId;

744
node_modules/mongoose/lib/utils.js generated vendored Normal file
View File

@@ -0,0 +1,744 @@
/*!
* Module dependencies.
*/
var ObjectId = require('./types/objectid');
var cloneRegExp = require('regexp-clone');
var sliced = require('sliced');
var mpath = require('mpath');
var ms = require('ms');
var MongooseBuffer;
var MongooseArray;
var Document;
/*!
* Produces a collection name from model `name`.
*
* @param {String} name a model name
* @return {String} a collection name
* @api private
*/
exports.toCollectionName = function (name, options) {
options = options || {};
if ('system.profile' === name) return name;
if ('system.indexes' === name) return name;
if (options.pluralization === false) return name;
return pluralize(name.toLowerCase());
};
/**
* Pluralization rules.
*
* These rules are applied while processing the argument to `toCollectionName`.
*
* @deprecated remove in 4.x gh-1350
*/
exports.pluralization = [
[/(m)an$/gi, '$1en'],
[/(pe)rson$/gi, '$1ople'],
[/(child)$/gi, '$1ren'],
[/^(ox)$/gi, '$1en'],
[/(ax|test)is$/gi, '$1es'],
[/(octop|vir)us$/gi, '$1i'],
[/(alias|status)$/gi, '$1es'],
[/(bu)s$/gi, '$1ses'],
[/(buffal|tomat|potat)o$/gi, '$1oes'],
[/([ti])um$/gi, '$1a'],
[/sis$/gi, 'ses'],
[/(?:([^f])fe|([lr])f)$/gi, '$1$2ves'],
[/(hive)$/gi, '$1s'],
[/([^aeiouy]|qu)y$/gi, '$1ies'],
[/(x|ch|ss|sh)$/gi, '$1es'],
[/(matr|vert|ind)ix|ex$/gi, '$1ices'],
[/([m|l])ouse$/gi, '$1ice'],
[/(kn|w|l)ife$/gi, '$1ives'],
[/(quiz)$/gi, '$1zes'],
[/s$/gi, 's'],
[/([^a-z])$/, '$1'],
[/$/gi, 's']
];
var rules = exports.pluralization;
/**
* Uncountable words.
*
* These words are applied while processing the argument to `toCollectionName`.
* @api public
*/
exports.uncountables = [
'advice',
'energy',
'excretion',
'digestion',
'cooperation',
'health',
'justice',
'labour',
'machinery',
'equipment',
'information',
'pollution',
'sewage',
'paper',
'money',
'species',
'series',
'rain',
'rice',
'fish',
'sheep',
'moose',
'deer',
'news',
'expertise',
'status',
'media'
];
var uncountables = exports.uncountables;
/*!
* Pluralize function.
*
* @author TJ Holowaychuk (extracted from _ext.js_)
* @param {String} string to pluralize
* @api private
*/
function pluralize (str) {
var rule, found;
if (!~uncountables.indexOf(str.toLowerCase())){
found = rules.filter(function(rule){
return str.match(rule[0]);
});
if (found[0]) return str.replace(found[0][0], found[0][1]);
}
return str;
};
/*!
* Determines if `a` and `b` are deep equal.
*
* Modified from node/lib/assert.js
*
* @param {any} a a value to compare to `b`
* @param {any} b a value to compare to `a`
* @return {Boolean}
* @api private
*/
exports.deepEqual = function deepEqual (a, b) {
if (a === b) return true;
if (a instanceof Date && b instanceof Date)
return a.getTime() === b.getTime();
if (a instanceof ObjectId && b instanceof ObjectId) {
return a.toString() === b.toString();
}
if (a instanceof RegExp && b instanceof RegExp) {
return a.source == b.source &&
a.ignoreCase == b.ignoreCase &&
a.multiline == b.multiline &&
a.global == b.global;
}
if (typeof a !== 'object' && typeof b !== 'object')
return a == b;
if (a === null || b === null || a === undefined || b === undefined)
return false
if (a.prototype !== b.prototype) return false;
// Handle MongooseNumbers
if (a instanceof Number && b instanceof Number) {
return a.valueOf() === b.valueOf();
}
if (Buffer.isBuffer(a)) {
return exports.buffer.areEqual(a, b);
}
if (isMongooseObject(a)) a = a.toObject();
if (isMongooseObject(b)) b = b.toObject();
try {
var ka = Object.keys(a),
kb = Object.keys(b),
key, i;
} catch (e) {//happens when one is a string literal and the other isn't
return false;
}
// having the same number of owned properties (keys incorporates
// hasOwnProperty)
if (ka.length != kb.length)
return false;
//the same set of keys (although not necessarily the same order),
ka.sort();
kb.sort();
//~~~cheap key test
for (i = ka.length - 1; i >= 0; i--) {
if (ka[i] != kb[i])
return false;
}
//equivalent values for every corresponding key, and
//~~~possibly expensive deep test
for (i = ka.length - 1; i >= 0; i--) {
key = ka[i];
if (!deepEqual(a[key], b[key])) return false;
}
return true;
};
/*!
* Object clone with Mongoose natives support.
*
* If options.minimize is true, creates a minimal data object. Empty objects and undefined values will not be cloned. This makes the data payload sent to MongoDB as small as possible.
*
* Functions are never cloned.
*
* @param {Object} obj the object to clone
* @param {Object} options
* @return {Object} the cloned object
* @api private
*/
exports.clone = function clone (obj, options) {
if (obj === undefined || obj === null)
return obj;
if (Array.isArray(obj))
return cloneArray(obj, options);
if (isMongooseObject(obj)) {
if (options && options.json && 'function' === typeof obj.toJSON) {
return obj.toJSON(options);
} else {
return obj.toObject(options);
}
}
if (obj.constructor) {
switch (exports.getFunctionName(obj.constructor)) {
case 'Object':
return cloneObject(obj, options);
case 'Date':
return new obj.constructor(+obj);
case 'RegExp':
return cloneRegExp(obj);
default:
// ignore
break;
}
}
if (obj instanceof ObjectId)
return new ObjectId(obj.id);
if (!obj.constructor && exports.isObject(obj)) {
// object created with Object.create(null)
return cloneObject(obj, options);
}
if (obj.valueOf)
return obj.valueOf();
};
var clone = exports.clone;
/*!
* ignore
*/
function cloneObject (obj, options) {
var retainKeyOrder = options && options.retainKeyOrder
, minimize = options && options.minimize
, ret = {}
, hasKeys
, keys
, val
, k
, i
if (retainKeyOrder) {
for (k in obj) {
val = clone(obj[k], options);
if (!minimize || ('undefined' !== typeof val)) {
hasKeys || (hasKeys = true);
ret[k] = val;
}
}
} else {
// faster
keys = Object.keys(obj);
i = keys.length;
while (i--) {
k = keys[i];
val = clone(obj[k], options);
if (!minimize || ('undefined' !== typeof val)) {
if (!hasKeys) hasKeys = true;
ret[k] = val;
}
}
}
return minimize
? hasKeys && ret
: ret;
};
function cloneArray (arr, options) {
var ret = [];
for (var i = 0, l = arr.length; i < l; i++)
ret.push(clone(arr[i], options));
return ret;
};
/*!
* Shallow copies defaults into options.
*
* @param {Object} defaults
* @param {Object} options
* @return {Object} the merged object
* @api private
*/
exports.options = function (defaults, options) {
var keys = Object.keys(defaults)
, i = keys.length
, k ;
options = options || {};
while (i--) {
k = keys[i];
if (!(k in options)) {
options[k] = defaults[k];
}
}
return options;
};
/*!
* Generates a random string
*
* @api private
*/
exports.random = function () {
return Math.random().toString().substr(3);
};
/*!
* Merges `from` into `to` without overwriting existing properties.
*
* @param {Object} to
* @param {Object} from
* @api private
*/
exports.merge = function merge (to, from) {
var keys = Object.keys(from)
, i = keys.length
, key;
while (i--) {
key = keys[i];
if ('undefined' === typeof to[key]) {
to[key] = from[key];
} else if (exports.isObject(from[key])) {
merge(to[key], from[key]);
}
}
};
/*!
* toString helper
*/
var toString = Object.prototype.toString;
/*!
* Determines if `arg` is an object.
*
* @param {Object|Array|String|Function|RegExp|any} arg
* @api private
* @return {Boolean}
*/
exports.isObject = function (arg) {
return '[object Object]' == toString.call(arg);
}
/*!
* A faster Array.prototype.slice.call(arguments) alternative
* @api private
*/
exports.args = sliced;
/*!
* process.nextTick helper.
*
* Wraps `callback` in a try/catch + nextTick.
*
* node-mongodb-native has a habit of state corruption when an error is immediately thrown from within a collection callback.
*
* @param {Function} callback
* @api private
*/
exports.tick = function tick (callback) {
if ('function' !== typeof callback) return;
return function () {
try {
callback.apply(this, arguments);
} catch (err) {
// only nextTick on err to get out of
// the event loop and avoid state corruption.
process.nextTick(function () {
throw err;
});
}
}
}
/*!
* Returns if `v` is a mongoose object that has a `toObject()` method we can use.
*
* This is for compatibility with libs like Date.js which do foolish things to Natives.
*
* @param {any} v
* @api private
*/
exports.isMongooseObject = function (v) {
Document || (Document = require('./document'));
MongooseArray || (MongooseArray = require('./types').Array);
MongooseBuffer || (MongooseBuffer = require('./types').Buffer);
return v instanceof Document ||
(v && v.isMongooseArray) ||
(v && v.isMongooseBuffer);
};
var isMongooseObject = exports.isMongooseObject;
/*!
* Converts `expires` options of index objects to `expiresAfterSeconds` options for MongoDB.
*
* @param {Object} object
* @api private
*/
exports.expires = function expires (object) {
if (!(object && 'Object' == object.constructor.name)) return;
if (!('expires' in object)) return;
var when;
if ('string' != typeof object.expires) {
when = object.expires;
} else {
when = Math.round(ms(object.expires) / 1000);
}
object.expireAfterSeconds = when;
delete object.expires;
};
/*!
* Populate options constructor
*/
function PopulateOptions (path, select, match, options, model) {
this.path = path;
this.match = match;
this.select = select;
this.options = options;
this.model = model;
this._docs = {};
}
// make it compatible with utils.clone
PopulateOptions.prototype.constructor = Object;
// expose
exports.PopulateOptions = PopulateOptions;
/*!
* populate helper
*/
exports.populate = function populate (path, select, model, match, options) {
// The order of select/conditions args is opposite Model.find but
// necessary to keep backward compatibility (select could be
// an array, string, or object literal).
// might have passed an object specifying all arguments
if (1 === arguments.length) {
if (path instanceof PopulateOptions) {
return [path];
}
if (Array.isArray(path)) {
return path.map(function(o){
return exports.populate(o)[0];
});
}
if (exports.isObject(path)) {
match = path.match;
options = path.options;
select = path.select;
model = path.model;
path = path.path;
}
} else if ('string' !== typeof model && 'function' !== typeof model) {
options = match;
match = model;
model = undefined;
}
if ('string' != typeof path) {
throw new TypeError('utils.populate: invalid path. Expected string. Got typeof `' + typeof path + '`');
}
var ret = [];
var paths = path.split(' ');
for (var i = 0; i < paths.length; ++i) {
ret.push(new PopulateOptions(paths[i], select, match, options, model));
}
return ret;
}
/*!
* Return the value of `obj` at the given `path`.
*
* @param {String} path
* @param {Object} obj
*/
exports.getValue = function (path, obj, map) {
return mpath.get(path, obj, '_doc', map);
}
/*!
* Sets the value of `obj` at the given `path`.
*
* @param {String} path
* @param {Anything} val
* @param {Object} obj
*/
exports.setValue = function (path, val, obj, map) {
mpath.set(path, val, obj, '_doc', map);
}
/*!
* Returns an array of values from object `o`.
*
* @param {Object} o
* @return {Array}
* @private
*/
exports.object = {};
exports.object.vals = function vals (o) {
var keys = Object.keys(o)
, i = keys.length
, ret = [];
while (i--) {
ret.push(o[keys[i]]);
}
return ret;
}
/*!
* @see exports.options
*/
exports.object.shallowCopy = exports.options;
/*!
* Safer helper for hasOwnProperty checks
*
* @param {Object} obj
* @param {String} prop
*/
var hop = Object.prototype.hasOwnProperty;
exports.object.hasOwnProperty = function (obj, prop) {
return hop.call(obj, prop);
}
/*!
* Determine if `val` is null or undefined
*
* @return {Boolean}
*/
exports.isNullOrUndefined = function (val) {
return null == val
}
/*!
* ignore
*/
exports.array = {};
/*!
* Flattens an array.
*
* [ 1, [ 2, 3, [4] ]] -> [1,2,3,4]
*
* @param {Array} arr
* @param {Function} [filter] If passed, will be invoked with each item in the array. If `filter` returns a falsey value, the item will not be included in the results.
* @return {Array}
* @private
*/
exports.array.flatten = function flatten (arr, filter, ret) {
ret || (ret = []);
arr.forEach(function (item) {
if (Array.isArray(item)) {
flatten(item, filter, ret);
} else {
if (!filter || filter(item)) {
ret.push(item);
}
}
});
return ret;
};
/*!
* Removes duplicate values from an array
*
* [1, 2, 3, 3, 5] => [1, 2, 3, 5]
* [ ObjectId("550988ba0c19d57f697dc45e"), ObjectId("550988ba0c19d57f697dc45e") ]
* => [ObjectId("550988ba0c19d57f697dc45e")]
*
* @param {Array} arr
* @return {Array}
* @private
*/
exports.array.unique = function(arr) {
var primitives = {};
var ids = {};
var ret = [];
var length = arr.length;
for (var i = 0; i < length; ++i) {
if (typeof arr[i] === 'number' || typeof arr[i] === 'string') {
if (primitives[arr[i]]) {
continue;
}
ret.push(arr[i]);
primitives[arr[i]] = true;
} else if (arr[i] instanceof ObjectId) {
if (ids[arr[i].toString()]) {
continue;
}
ret.push(arr[i]);
ids[arr[i].toString()] = true;
} else {
ret.push(arr[i]);
}
}
return ret;
};
/*!
* Determines if two buffers are equal.
*
* @param {Buffer} a
* @param {Object} b
*/
exports.buffer = {};
exports.buffer.areEqual = function (a, b) {
if (!Buffer.isBuffer(a)) return false;
if (!Buffer.isBuffer(b)) return false;
if (a.length !== b.length) return false;
for (var i = 0, len = a.length; i < len; ++i) {
if (a[i] !== b[i]) return false;
}
return true;
};
exports.getFunctionName = function(fn) {
if (fn.name) {
return fn.name;
}
return (fn.toString().trim().match(/^function\s*([^\s(]+)/) || [])[1];
};
exports.decorate = function(destination, source) {
for (var key in source) {
destination[key] = source[key];
}
};
/**
* merges to with a copy of from
*
* @param {Object} to
* @param {Object} from
* @api private
*/
exports.mergeClone = function(to, from) {
var keys = Object.keys(from)
, i = keys.length
, key
while (i--) {
key = keys[i];
if ('undefined' === typeof to[key]) {
// make sure to retain key order here because of a bug handling the $each
// operator in mongodb 2.4.4
to[key] = exports.clone(from[key], { retainKeyOrder : 1});
} else {
if (exports.isObject(from[key])) {
exports.mergeClone(to[key], from[key]);
} else {
// make sure to retain key order here because of a bug handling the
// $each operator in mongodb 2.4.4
to[key] = exports.clone(from[key], { retainKeyOrder : 1});
}
}
}
};
/**
* Executes a function on each element of an array (like _.each)
*
* @param {Array} arr
* @param {Function} fn
* @api private
*/
exports.each = function(arr, fn) {
for (var i = 0; i < arr.length; ++i) {
fn(arr[i]);
}
};

103
node_modules/mongoose/lib/virtualtype.js generated vendored Normal file
View File

@@ -0,0 +1,103 @@
/**
* VirtualType constructor
*
* This is what mongoose uses to define virtual attributes via `Schema.prototype.virtual`.
*
* ####Example:
*
* var fullname = schema.virtual('fullname');
* fullname instanceof mongoose.VirtualType // true
*
* @parma {Object} options
* @api public
*/
function VirtualType (options, name) {
this.path = name;
this.getters = [];
this.setters = [];
this.options = options || {};
}
/**
* Defines a getter.
*
* ####Example:
*
* var virtual = schema.virtual('fullname');
* virtual.get(function () {
* return this.name.first + ' ' + this.name.last;
* });
*
* @param {Function} fn
* @return {VirtualType} this
* @api public
*/
VirtualType.prototype.get = function (fn) {
this.getters.push(fn);
return this;
};
/**
* Defines a setter.
*
* ####Example:
*
* var virtual = schema.virtual('fullname');
* virtual.set(function (v) {
* var parts = v.split(' ');
* this.name.first = parts[0];
* this.name.last = parts[1];
* });
*
* @param {Function} fn
* @return {VirtualType} this
* @api public
*/
VirtualType.prototype.set = function (fn) {
this.setters.push(fn);
return this;
};
/**
* Applies getters to `value` using optional `scope`.
*
* @param {Object} value
* @param {Object} scope
* @return {any} the value after applying all getters
* @api public
*/
VirtualType.prototype.applyGetters = function (value, scope) {
var v = value;
for (var l = this.getters.length - 1; l >= 0; l--) {
v = this.getters[l].call(scope, v, this);
}
return v;
};
/**
* Applies setters to `value` using optional `scope`.
*
* @param {Object} value
* @param {Object} scope
* @return {any} the value after applying all setters
* @api public
*/
VirtualType.prototype.applySetters = function (value, scope) {
var v = value;
for (var l = this.setters.length - 1; l >= 0; l--) {
v = this.setters[l].call(scope, v, this);
}
return v;
};
/*!
* exports
*/
module.exports = VirtualType;