summaryrefslogtreecommitdiffstats
path: root/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib
diff options
context:
space:
mode:
authorlizi00164331 <li.zi30@zte.com.cn>2017-08-07 11:39:39 +0800
committerlizi00164331 <li.zi30@zte.com.cn>2017-08-07 11:39:39 +0800
commit21d72c4a80fe2937d0c4ddd20624b27adbcd989b (patch)
treee5013ee12f74f8452e01cbff16e7b0158bc456cb /common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib
parentf533e73e2ae32e010b16abdcf7985abaf31ab843 (diff)
Upload the ESR GUI seed code
Issue-ID: AAI-68 Change-Id: Ia50ce0570c2fabecd77199d4e8454f56fe587c4e Signed-off-by: lizi00164331 <li.zi30@zte.com.cn>
Diffstat (limited to 'common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib')
-rw-r--r--common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/ES6Promise.js26
-rw-r--r--common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/aggregate.js685
-rw-r--r--common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/browser.js126
-rw-r--r--common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/browserDocument.js103
-rw-r--r--common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/cast.js248
-rw-r--r--common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/collection.js210
-rw-r--r--common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/connection.js854
-rw-r--r--common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/connectionstate.js27
-rw-r--r--common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/document.js2615
-rw-r--r--common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/document_provider.js21
-rw-r--r--common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/document_provider.web.js17
-rw-r--r--common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/drivers/SPEC.md4
-rw-r--r--common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/drivers/browser/ReadPreference.js5
-rw-r--r--common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/drivers/browser/binary.js12
-rw-r--r--common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/drivers/browser/index.js7
-rw-r--r--common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/drivers/browser/objectid.js14
-rw-r--r--common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/drivers/index.js17
-rw-r--r--common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/drivers/index.web.js5
-rw-r--r--common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/drivers/node-mongodb-native/ReadPreference.js45
-rw-r--r--common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/drivers/node-mongodb-native/binary.js8
-rw-r--r--common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/drivers/node-mongodb-native/collection.js267
-rw-r--r--common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/drivers/node-mongodb-native/connection.js386
-rw-r--r--common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/drivers/node-mongodb-native/index.js7
-rw-r--r--common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/drivers/node-mongodb-native/objectid.js14
-rw-r--r--common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/error.js55
-rw-r--r--common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/error/browserMissingSchema.js32
-rw-r--r--common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/error/cast.js60
-rw-r--r--common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/error/disconnected.js40
-rw-r--r--common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/error/divergentArray.js42
-rw-r--r--common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/error/messages.js42
-rw-r--r--common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/error/missingSchema.js33
-rw-r--r--common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/error/objectExpected.js35
-rw-r--r--common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/error/overwriteModel.js31
-rw-r--r--common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/error/strict.js35
-rw-r--r--common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/error/validation.js63
-rw-r--r--common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/error/validator.js81
-rw-r--r--common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/error/version.js33
-rw-r--r--common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/index.js818
-rw-r--r--common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/internal.js31
-rw-r--r--common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/model.js3414
-rw-r--r--common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/promise.js314
-rw-r--r--common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/promise_provider.js51
-rw-r--r--common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/query.js3413
-rw-r--r--common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/querycursor.js314
-rw-r--r--common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/queryhelpers.js78
-rw-r--r--common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/querystream.js367
-rw-r--r--common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/schema.js1768
-rw-r--r--common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/schema/array.js314
-rw-r--r--common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/schema/boolean.js103
-rw-r--r--common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/schema/buffer.js188
-rw-r--r--common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/schema/date.js296
-rw-r--r--common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/schema/documentarray.js313
-rw-r--r--common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/schema/embedded.js177
-rw-r--r--common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/schema/index.js30
-rw-r--r--common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/schema/mixed.js80
-rw-r--r--common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/schema/number.js290
-rw-r--r--common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/schema/objectid.js207
-rw-r--r--common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/schema/operators/bitwise.js36
-rw-r--r--common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/schema/operators/geospatial.js100
-rw-r--r--common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/schema/operators/helpers.js34
-rw-r--r--common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/schema/string.js516
-rw-r--r--common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/schematype.js931
-rw-r--r--common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/services/common.js87
-rw-r--r--common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/services/setDefaultsOnInsert.js96
-rw-r--r--common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/services/updateValidators.js100
-rw-r--r--common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/statemachine.js178
-rw-r--r--common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/types/array.js778
-rw-r--r--common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/types/buffer.js273
-rw-r--r--common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/types/documentarray.js256
-rw-r--r--common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/types/embedded.js347
-rw-r--r--common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/types/index.js15
-rw-r--r--common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/types/objectid.js13
-rw-r--r--common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/types/subdocument.js152
-rw-r--r--common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/utils.js868
-rw-r--r--common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/virtualtype.js103
75 files changed, 23754 insertions, 0 deletions
diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/ES6Promise.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/ES6Promise.js
new file mode 100644
index 0000000..13371ac
--- /dev/null
+++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/ES6Promise.js
@@ -0,0 +1,26 @@
+/**
+ * ES6 Promise wrapper constructor.
+ *
+ * Promises are returned from executed queries. Example:
+ *
+ * var query = Candy.find({ bar: true });
+ * var promise = query.exec();
+ *
+ * DEPRECATED. Mongoose 5.0 will use native promises by default (or bluebird,
+ * if native promises are not present) but still
+ * support plugging in your own ES6-compatible promises library. Mongoose 5.0
+ * will **not** support mpromise.
+ *
+ * @param {Function} fn a function which will be called when the promise is resolved that accepts `fn(err, ...){}` as signature
+ * @api public
+ */
+
+function ES6Promise() {
+ throw new Error('Can\'t use ES6 promise with mpromise style constructor');
+}
+
+ES6Promise.use = function(Promise) {
+ ES6Promise.ES6 = Promise;
+};
+
+module.exports = ES6Promise;
diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/aggregate.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/aggregate.js
new file mode 100644
index 0000000..bb24e88
--- /dev/null
+++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/aggregate.js
@@ -0,0 +1,685 @@
+/*!
+ * Module dependencies
+ */
+
+var util = require('util');
+var utils = require('./utils');
+var PromiseProvider = require('./promise_provider');
+var Query = require('./query');
+var 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
+ * - Mongoose does **not** cast pipeline stages. `new Aggregate({ $match: { _id: '00000000000000000000000a' } });` will not work unless `_id` is a string in the database. Use `new Aggregate({ $match: { _id: mongoose.Types.ObjectId('00000000000000000000000a') } });` instead.
+ *
+ * @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 (arguments.length === 1 && 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 public
+ */
+
+Aggregate.prototype.model = 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 = (arguments.length === 1 && util.isArray(arguments[0]))
+ ? arguments[0]
+ : utils.args(arguments);
+
+ 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 (typeof arg === 'object' && !util.isArray(arg)) {
+ Object.keys(arg).forEach(function(field) {
+ fields[field] = arg[field];
+ });
+ } else if (arguments.length === 1 && typeof arg === 'string') {
+ 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.
+ *
+ * Note that the `$unwind` operator requires the path name to start with '$'.
+ * Mongoose will prepend '$' if the specified field doesn't start '$'.
+ *
+ * ####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);
+
+ var res = [];
+ for (var i = 0; i < args.length; ++i) {
+ var arg = args[i];
+ if (arg && typeof arg === 'object') {
+ res.push({ $unwind: arg });
+ } else if (typeof arg === 'string') {
+ res.push({
+ $unwind: (arg && arg.charAt(0) === '$') ? arg : '$' + arg
+ });
+ } else {
+ throw new Error('Invalid arg "' + arg + '" to unwind(), ' +
+ 'must be string or object');
+ }
+ }
+
+ return this.append.apply(this, res);
+};
+
+/**
+ * Appends new custom $lookup operator(s) to this aggregate pipeline.
+ *
+ * ####Examples:
+ *
+ * aggregate.lookup({ from: 'users', localField: 'userId', foreignField: '_id', as: 'users' });
+ *
+ * @see $lookup https://docs.mongodb.org/manual/reference/operator/aggregation/lookup/#pipe._S_lookup
+ * @param {Object} options to $lookup as described in the above link
+ * @return {Aggregate}
+ * @api public
+ */
+
+Aggregate.prototype.lookup = function(options) {
+ return this.append({$lookup: options});
+};
+
+/**
+ * Appends new custom $sample operator(s) to this aggregate pipeline.
+ *
+ * ####Examples:
+ *
+ * aggregate.sample(3); // Add a pipeline that picks 3 random documents
+ *
+ * @see $sample https://docs.mongodb.org/manual/reference/operator/aggregation/sample/#pipe._S_sample
+ * @param {Number} size number of random documents to pick
+ * @return {Aggregate}
+ * @api public
+ */
+
+Aggregate.prototype.sample = function(size) {
+ return this.append({$sample: {size: size}});
+};
+
+/**
+ * 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 (arg.constructor.name === 'Object') {
+ var desc = ['desc', 'descending', -1];
+ Object.keys(arg).forEach(function(field) {
+ sort[field] = desc.indexOf(arg[field]) === -1 ? 1 : -1;
+ });
+ } else if (arguments.length === 1 && typeof arg === 'string') {
+ 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, tags) {
+ if (!this.options) {
+ this.options = {};
+ }
+ read.call(this, pref, tags);
+ return this;
+};
+
+/**
+ * Execute the aggregation with explain
+ *
+ * ####Example:
+ *
+ * Model.aggregate(..).explain(callback)
+ *
+ * @param {Function} callback
+ * @return {Promise}
+ */
+
+Aggregate.prototype.explain = function(callback) {
+ var _this = this;
+ var Promise = PromiseProvider.get();
+ return new Promise.ES6(function(resolve, reject) {
+ if (!_this._pipeline.length) {
+ var err = new Error('Aggregate has empty pipeline');
+ if (callback) {
+ callback(err);
+ }
+ reject(err);
+ return;
+ }
+
+ prepareDiscriminatorPipeline(_this);
+
+ _this._model
+ .collection
+ .aggregate(_this._pipeline, _this.options || {})
+ .explain(function(error, result) {
+ if (error) {
+ if (callback) {
+ callback(error);
+ }
+ reject(error);
+ return;
+ }
+
+ if (callback) {
+ callback(null, result);
+ }
+ resolve(result);
+ });
+ });
+};
+
+/**
+ * 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;
+};
+
+/**
+ * Adds a [cursor flag](http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#addCursorFlag)
+ *
+ * ####Example:
+ *
+ * var cursor = Model.aggregate(..).cursor({ batchSize: 1000 }).exec();
+ * cursor.each(function(error, doc) {
+ * // use doc
+ * });
+ *
+ * @param {String} flag
+ * @param {Boolean} value
+ * @see mongodb http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#addCursorFlag
+ */
+
+Aggregate.prototype.addCursorFlag = function(flag, value) {
+ if (!this.options) {
+ this.options = {};
+ }
+ this.options[flag] = value;
+ 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) {
+ if (!this._model) {
+ throw new Error('Aggregate not bound to any Model');
+ }
+ var _this = this;
+ var Promise = PromiseProvider.get();
+ var options = utils.clone(this.options);
+
+ if (options && options.cursor) {
+ if (options.cursor.async) {
+ delete options.cursor.async;
+ return new Promise.ES6(function(resolve) {
+ if (!_this._model.collection.buffer) {
+ process.nextTick(function() {
+ var cursor = _this._model.collection.
+ aggregate(_this._pipeline, options || {});
+ resolve(cursor);
+ callback && callback(null, cursor);
+ });
+ return;
+ }
+ _this._model.collection.emitter.once('queue', function() {
+ var cursor = _this._model.collection.
+ aggregate(_this._pipeline, options || {});
+ resolve(cursor);
+ callback && callback(null, cursor);
+ });
+ });
+ }
+ return this._model.collection.
+ aggregate(this._pipeline, this.options || {});
+ }
+
+ return new Promise.ES6(function(resolve, reject) {
+ if (!_this._pipeline.length) {
+ var err = new Error('Aggregate has empty pipeline');
+ if (callback) {
+ callback(err);
+ }
+ reject(err);
+ return;
+ }
+
+ prepareDiscriminatorPipeline(_this);
+
+ _this._model
+ .collection
+ .aggregate(_this._pipeline, _this.options || {}, function(error, result) {
+ if (error) {
+ if (callback) {
+ callback(error);
+ }
+ reject(error);
+ return;
+ }
+
+ if (callback) {
+ callback(null, result);
+ }
+ resolve(result);
+ });
+ });
+};
+
+/**
+ * Provides promise for aggregate.
+ *
+ * ####Example:
+ *
+ * Model.aggregate(..).then(successCallback, errorCallback);
+ *
+ * @see Promise #promise_Promise
+ * @param {Function} [resolve] successCallback
+ * @param {Function} [reject] errorCallback
+ * @return {Promise}
+ */
+Aggregate.prototype.then = function(resolve, reject) {
+ var _this = this;
+ var Promise = PromiseProvider.get();
+ var promise = new Promise.ES6(function(success, error) {
+ _this.exec(function(err, val) {
+ if (err) error(err);
+ else success(val);
+ });
+ });
+ return promise.then(resolve, reject);
+};
+
+/*!
+ * 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 (typeof obj !== 'object') {
+ return false;
+ }
+
+ k = Object.keys(obj);
+
+ return k.length === 1 && 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 if (originalPipeline[0] && originalPipeline[0].$geoNear) {
+ originalPipeline[0].$geoNear.query =
+ originalPipeline[0].$geoNear.query || {};
+ originalPipeline[0].$geoNear.query[discriminatorKey] = discriminatorValue;
+ } else {
+ var match = {};
+ match[discriminatorKey] = discriminatorValue;
+ aggregate._pipeline = [{$match: match}].concat(originalPipeline);
+ }
+ }
+}
+
+
+/*!
+ * Exports
+ */
+
+module.exports = Aggregate;
diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/browser.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/browser.js
new file mode 100644
index 0000000..a787539
--- /dev/null
+++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/browser.js
@@ -0,0 +1,126 @@
+/* eslint-env browser */
+
+var PromiseProvider = require('./promise_provider');
+
+/**
+ * The Mongoose [Promise](#promise_Promise) constructor.
+ *
+ * @method Promise
+ * @api public
+ */
+
+Object.defineProperty(exports, 'Promise', {
+ get: function() {
+ return PromiseProvider.get();
+ },
+ set: function(lib) {
+ PromiseProvider.set(lib);
+ }
+});
+
+/**
+ * Storage layer for mongoose promises
+ *
+ * @method PromiseProvider
+ * @api public
+ */
+
+exports.PromiseProvider = PromiseProvider;
+
+/**
+ * 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;
+}
diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/browserDocument.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/browserDocument.js
new file mode 100644
index 0000000..6c87d19
--- /dev/null
+++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/browserDocument.js
@@ -0,0 +1,103 @@
+/*!
+ * Module dependencies.
+ */
+
+var NodeJSDocument = require('./document'),
+ EventEmitter = require('events').EventEmitter,
+ MongooseError = require('./error'),
+ Schema = require('./schema'),
+ ObjectId = require('./types/objectid'),
+ utils = require('./utils'),
+ ValidationError = MongooseError.ValidationError,
+ InternalCache = require('./internal');
+
+/**
+ * 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 retrieved 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.instanceOfSchema) {
+ 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 (typeof fields === 'boolean') {
+ 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]);
+ }
+
+ this.$__.emitter.setMaxListeners(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;
diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/cast.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/cast.js
new file mode 100644
index 0000000..6a07196
--- /dev/null
+++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/cast.js
@@ -0,0 +1,248 @@
+/*!
+ * Module dependencies.
+ */
+
+var utils = require('./utils');
+var Types = require('./schema/index');
+
+var ALLOWED_GEOWITHIN_GEOJSON_TYPES = ['Polygon', 'MultiPolygon'];
+
+/**
+ * Handles internal casting for queries
+ *
+ * @param {Schema} schema
+ * @param {Object} obj Object to cast
+ * @api private
+ */
+module.exports = function cast(schema, obj) {
+ var paths = Object.keys(obj),
+ i = paths.length,
+ _keys,
+ any$conditionals,
+ schematype,
+ nested,
+ path,
+ type,
+ val;
+
+ while (i--) {
+ path = paths[i];
+ val = obj[path];
+
+ if (path === '$or' || path === '$nor' || path === '$and') {
+ var k = val.length;
+
+ while (k--) {
+ val[k] = cast(schema, val[k]);
+ }
+ } else if (path === '$where') {
+ type = typeof val;
+
+ if (type !== 'string' && type !== 'function') {
+ throw new Error('Must have a string or function for $where');
+ }
+
+ if (type === 'function') {
+ obj[path] = val.toString();
+ }
+
+ continue;
+ } else if (path === '$elemMatch') {
+ val = cast(schema, val);
+ } 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;
+
+ // 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 = '';
+ if (val.$near) {
+ geo = '$near';
+ } else if (val.$nearSphere) {
+ geo = '$nearSphere';
+ } else if (val.$within) {
+ geo = '$within';
+ } else if (val.$geoIntersects) {
+ geo = '$geoIntersects';
+ } else if (val.$geoWithin) {
+ geo = '$geoWithin';
+ }
+
+ if (!geo) {
+ continue;
+ }
+
+ var numbertype = new Types.Number('__QueryCasting__');
+ var value = val[geo];
+
+ if (val.$maxDistance != null) {
+ val.$maxDistance = numbertype.castForQuery(val.$maxDistance);
+ }
+ if (val.$minDistance != null) {
+ val.$minDistance = numbertype.castForQuery(val.$minDistance);
+ }
+
+ if (geo === '$within') {
+ 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 (geo === '$near' &&
+ typeof value.type === 'string' && Array.isArray(value.coordinates)) {
+ // geojson; cast the coordinates
+ value = value.coordinates;
+ } else if ((geo === '$near' || geo === '$nearSphere' || geo === '$geoIntersects') &&
+ value.$geometry && typeof value.$geometry.type === 'string' &&
+ Array.isArray(value.$geometry.coordinates)) {
+ if (value.$maxDistance != null) {
+ value.$maxDistance = numbertype.castForQuery(value.$maxDistance);
+ }
+ if (value.$minDistance != null) {
+ value.$minDistance = numbertype.castForQuery(value.$minDistance);
+ }
+ if (utils.isMongooseObject(value.$geometry)) {
+ value.$geometry = value.$geometry.toObject({ transform: false });
+ }
+ value = value.$geometry.coordinates;
+ } else if (geo === '$geoWithin') {
+ if (value.$geometry) {
+ if (utils.isMongooseObject(value.$geometry)) {
+ value.$geometry = value.$geometry.toObject({ virtuals: false });
+ }
+ var geoWithinType = value.$geometry.type;
+ if (ALLOWED_GEOWITHIN_GEOJSON_TYPES.indexOf(geoWithinType) === -1) {
+ throw new Error('Invalid geoJSON type for $geoWithin "' +
+ geoWithinType + '", must be "Polygon" or "MultiPolygon"');
+ }
+ value = value.$geometry.coordinates;
+ } else {
+ value = value.$box || value.$polygon || value.$center ||
+ value.$centerSphere;
+ if (utils.isMongooseObject(value)) {
+ value = value.toObject({ virtuals: false });
+ }
+ }
+ }
+
+ _cast(value, numbertype);
+ }
+ } else if (val === null || val === undefined) {
+ obj[path] = null;
+ continue;
+ } else if (val.constructor.name === 'Object') {
+ 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),
+ $cond;
+
+ k = ks.length;
+
+ while (k--) {
+ $cond = ks[k];
+ nested = val[$cond];
+
+ if ($cond === '$exists') {
+ if (typeof nested !== 'boolean') {
+ throw new Error('$exists parameter must be Boolean');
+ }
+ continue;
+ }
+
+ if ($cond === '$not') {
+ if (nested && schematype && !schematype.caster) {
+ _keys = Object.keys(nested);
+ if (_keys.length && _keys[0].charAt(0) === '$') {
+ for (var key in nested) {
+ nested[key] = schematype.castForQuery(key, nested[key]);
+ }
+ } else {
+ val[$cond] = schematype.castForQuery($cond, nested);
+ }
+ continue;
+ }
+ cast(schematype.caster ? schematype.caster.schema : schema, nested);
+ } else {
+ val[$cond] = schematype.castForQuery($cond, nested);
+ }
+ }
+ }
+ } else {
+ obj[path] = schematype.castForQuery(val);
+ }
+ }
+ }
+
+ return obj;
+};
+
+function _cast(val, numbertype) {
+ if (Array.isArray(val)) {
+ val.forEach(function(item, i) {
+ if (Array.isArray(item) || utils.isObject(item)) {
+ return _cast(item, numbertype);
+ }
+ 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, numbertype);
+ val[nkey] = item;
+ } else {
+ val[nkey] = numbertype.castForQuery(item);
+ }
+ }
+ }
+}
diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/collection.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/collection.js
new file mode 100644
index 0000000..e550ec2
--- /dev/null
+++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/collection.js
@@ -0,0 +1,210 @@
+/*!
+ * Module dependencies.
+ */
+
+var EventEmitter = require('events').EventEmitter;
+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 (opts === void 0) {
+ opts = {};
+ }
+ if (opts.capped === void 0) {
+ opts.capped = {};
+ }
+
+ opts.bufferCommands = undefined === opts.bufferCommands
+ ? true
+ : opts.bufferCommands;
+
+ if (typeof opts.capped === 'number') {
+ opts.capped = {size: opts.capped};
+ }
+
+ this.opts = opts;
+ this.name = name;
+ this.collectionName = name;
+ this.conn = conn;
+ this.queue = [];
+ this.buffer = this.opts.bufferCommands;
+ this.emitter = new EventEmitter();
+
+ 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() {
+ this.buffer = false;
+ this.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++) {
+ if (typeof this.queue[i][0] === 'function') {
+ this.queue[i][0].apply(this, this.queue[i][1]);
+ } else {
+ this[this.queue[i][0]].apply(this, this.queue[i][1]);
+ }
+ }
+ this.queue = [];
+ var _this = this;
+ process.nextTick(function() {
+ _this.emitter.emit('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;
diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/connection.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/connection.js
new file mode 100644
index 0000000..69c470a
--- /dev/null
+++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/connection.js
@@ -0,0 +1,854 @@
+/*!
+ * Module dependencies.
+ */
+
+var utils = require('./utils');
+var EventEmitter = require('events').EventEmitter;
+var driver = global.MONGOOSE_DRIVER_PATH || './drivers/node-mongodb-native';
+var Schema = require('./schema');
+var Collection = require(driver + '/collection');
+var STATES = require('./connectionstate');
+var MongooseError = require('./error');
+var muri = require('muri');
+var PromiseProvider = require('./promise_provider');
+
+/*!
+ * Protocol prefix regexp.
+ *
+ * @api private
+ */
+
+var rgxProtocol = /^(?:.)+:\/\//;
+
+/*!
+ * A list of authentication mechanisms that don't require a password for authentication.
+ * This is used by the authMechanismDoesNotRequirePassword method.
+ *
+ * @api private
+ */
+var authMechanismsWhichDontRequirePassword = [
+ 'MONGODB-X509'
+];
+
+/**
+ * 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 primary and at least one seconaries specified in the connection string are connected.
+ * @event `all`: 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 config
+ */
+
+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 parsed;
+ var Promise = PromiseProvider.get();
+
+ if (typeof database === 'string') {
+ switch (arguments.length) {
+ case 2:
+ port = 27017;
+ break;
+ case 3:
+ switch (typeof port) {
+ case 'function':
+ callback = port;
+ port = 27017;
+ break;
+ case 'object':
+ options = port;
+ port = 27017;
+ break;
+ }
+ break;
+ case 4:
+ if (typeof options === 'function') {
+ 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 new Promise.ES6(function(resolve, reject) {
+ reject(err);
+ });
+ }
+
+ if (!host) {
+ this.error(new Error('Missing hostname.'), callback);
+ return new Promise.ES6(function(resolve, reject) {
+ reject(err);
+ });
+ }
+
+ if (!database) {
+ this.error(new Error('Missing database name.'), callback);
+ return new Promise.ES6(function(resolve, reject) {
+ reject(err);
+ });
+ }
+
+ // authentication
+ if (this.optionsProvideAuthenticationData(options)) {
+ 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) {
+ this.config.autoIndex = options.config.autoIndex !== false;
+ }
+
+ this.name = database;
+ this.host = host;
+ this.port = port;
+
+ var _this = this;
+ var promise = new Promise.ES6(function(resolve, reject) {
+ _this._open(true, function(error) {
+ callback && callback(error);
+ if (error) {
+ reject(error);
+ if (!callback && !promise.$hasHandler) {
+ _this.emit('error', error);
+ }
+ return;
+ }
+ resolve();
+ });
+ });
+ return promise;
+};
+
+/**
+ * Helper for `dropDatabase()`.
+ *
+ * @param {Function} callback
+ * @return {Promise}
+ * @api public
+ */
+
+Connection.prototype.dropDatabase = function(callback) {
+ var Promise = PromiseProvider.get();
+ var _this = this;
+ var promise = new Promise.ES6(function(resolve, reject) {
+ if (_this.readyState !== STATES.connected) {
+ _this.on('open', function() {
+ _this.db.dropDatabase(function(error) {
+ if (error) {
+ reject(error);
+ } else {
+ resolve();
+ }
+ });
+ });
+ } else {
+ _this.db.dropDatabase(function(error) {
+ if (error) {
+ reject(error);
+ } else {
+ resolve();
+ }
+ });
+ }
+ });
+ if (callback) {
+ promise.then(function() { callback(); }, callback);
+ }
+ return promise;
+};
+
+/**
+ * Opens the connection to a replica set.
+ *
+ * ####Example:
+ *
+ * var db = mongoose.createConnection();
+ * db.openSet("mongodb://user:pwd@localhost:27020,localhost:27021,localhost:27012/mydb");
+ *
+ * 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 MongoDB connection string
+ * @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 Promise = PromiseProvider.get();
+
+ switch (arguments.length) {
+ case 3:
+ switch (typeof database) {
+ case 'string':
+ this.name = database;
+ break;
+ case 'object':
+ callback = options;
+ options = database;
+ database = null;
+ break;
+ }
+
+ if (typeof options === 'function') {
+ 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;
+ }
+ }
+
+ if (typeof database === 'string') {
+ this.name = database;
+ }
+
+ var parsed;
+ try {
+ parsed = muri(uris);
+ } catch (err) {
+ this.error(err, callback);
+ return new Promise.ES6(function(resolve, reject) {
+ reject(err);
+ });
+ }
+
+ 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) {
+ var err = new Error('No database name provided for replica set');
+ this.error(err, callback);
+ return new Promise.ES6(function(resolve, reject) {
+ reject(err);
+ });
+ }
+
+ // authentication
+ if (this.optionsProvideAuthenticationData(options)) {
+ 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) {
+ this.config.autoIndex = options.config.autoIndex !== false;
+ }
+
+ var _this = this;
+ var emitted = false;
+ var promise = new Promise.ES6(function(resolve, reject) {
+ _this._open(true, function(error) {
+ callback && callback(error);
+ if (error) {
+ reject(error);
+ if (!callback && !promise.$hasHandler && !emitted) {
+ emitted = true;
+ _this.emit('error', error);
+ }
+ return;
+ }
+ resolve();
+ });
+ });
+ return promise;
+};
+
+/**
+ * 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(emit, callback) {
+ this.readyState = STATES.connecting;
+ this._closeCalled = false;
+
+ var _this = this;
+
+ var method = this.replica
+ ? 'doOpenSet'
+ : 'doOpen';
+
+ // open connection
+ this[method](function(err) {
+ if (err) {
+ _this.readyState = STATES.disconnected;
+ if (_this._hasOpened) {
+ if (callback) {
+ callback(err);
+ }
+ } else {
+ _this.error(err, emit && callback);
+ }
+ return;
+ }
+
+ _this.onOpen(callback);
+ });
+};
+
+/**
+ * Called when the connection is opened
+ *
+ * @api private
+ */
+
+Connection.prototype.onOpen = function(callback) {
+ var _this = this;
+
+ function open(err, isAuth) {
+ if (err) {
+ _this.readyState = isAuth ? STATES.unauthorized : STATES.disconnected;
+ _this.error(err, callback);
+ return;
+ }
+
+ _this.readyState = STATES.connected;
+
+ // avoid having the collection subscribe to our event emitter
+ // to prevent 0.3 warning
+ for (var i in _this.collections) {
+ if (utils.object.hasOwnProperty(_this.collections, i)) {
+ _this.collections[i].onOpen();
+ }
+ }
+
+ callback && callback();
+ _this.emit('open');
+ }
+
+ // re-authenticate if we're not already connected #3871
+ if (this._readyState !== STATES.connected && this.shouldAuthenticate()) {
+ _this.db.authenticate(_this.user, _this.pass, _this.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 _this = this;
+ var Promise = PromiseProvider.get();
+ return new Promise.ES6(function(resolve, reject) {
+ _this._close(function(error) {
+ callback && callback(error);
+ if (error) {
+ reject(error);
+ return;
+ }
+ resolve();
+ });
+ });
+};
+
+/**
+ * Handles closing the connection
+ *
+ * @param {Function} callback
+ * @api private
+ */
+Connection.prototype._close = function(callback) {
+ var _this = 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) {
+ _this.error(err, callback);
+ } else {
+ _this.onClose();
+ callback && callback();
+ }
+ });
+ break;
+
+ case 2: // connecting
+ this.once('open', function() {
+ _this.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) {
+ if (utils.object.hasOwnProperty(this.collections, i)) {
+ 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 (typeof schema === 'string') {
+ collection = schema;
+ schema = false;
+ }
+
+ if (utils.isObject(schema) && !schema.instanceOfSchema) {
+ schema = new Schema(schema);
+ }
+ if (schema && !schema.instanceOfSchema) {
+ throw new Error('The 2nd parameter to `mongoose.model()` should be a ' +
+ 'schema or a POJO');
+ }
+
+ if (this.models[name] && !collection) {
+ // model exists but we are not subclassing with custom collection
+ if (schema && schema.instanceOfSchema && schema !== this.models[name].schema) {
+ throw new MongooseError.OverwriteModelError(name);
+ }
+ return this.models[name];
+ }
+
+ var opts = {cache: false, connection: this};
+ var model;
+
+ if (schema && schema.instanceOfSchema) {
+ // 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;
+ }
+ this.models[name] = model.__subclass(this, schema, collection);
+ return this.models[name];
+};
+
+/**
+ * Returns an array of model names created on this connection.
+ * @api public
+ * @return {Array}
+ */
+
+Connection.prototype.modelNames = function() {
+ return Object.keys(this.models);
+};
+
+/**
+ * @brief Returns if the connection requires authentication after it is opened. Generally if a
+ * username and password are both provided than authentication is needed, but in some cases a
+ * password is not required.
+ * @api private
+ * @return {Boolean} true if the connection should be authenticated after it is opened, otherwise false.
+ */
+Connection.prototype.shouldAuthenticate = function() {
+ return (this.user !== null && this.user !== void 0) &&
+ ((this.pass !== null || this.pass !== void 0) || this.authMechanismDoesNotRequirePassword());
+};
+
+/**
+ * @brief Returns a boolean value that specifies if the current authentication mechanism needs a
+ * password to authenticate according to the auth objects passed into the open/openSet methods.
+ * @api private
+ * @return {Boolean} true if the authentication mechanism specified in the options object requires
+ * a password, otherwise false.
+ */
+Connection.prototype.authMechanismDoesNotRequirePassword = function() {
+ if (this.options && this.options.auth) {
+ return authMechanismsWhichDontRequirePassword.indexOf(this.options.auth.authMechanism) >= 0;
+ }
+ return true;
+};
+
+/**
+ * @brief Returns a boolean value that specifies if the provided objects object provides enough
+ * data to authenticate with. Generally this is true if the username and password are both specified
+ * but in some authentication methods, a password is not required for authentication so only a username
+ * is required.
+ * @param {Object} [options] the options object passed into the open/openSet methods.
+ * @api private
+ * @return {Boolean} true if the provided options object provides enough data to authenticate with,
+ * otherwise false.
+ */
+Connection.prototype.optionsProvideAuthenticationData = function(options) {
+ return (options) &&
+ (options.user) &&
+ ((options.pass) || this.authMechanismDoesNotRequirePassword());
+};
+
+/*!
+ * Module exports.
+ */
+
+Connection.STATES = STATES;
+module.exports = Connection;
diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/connectionstate.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/connectionstate.js
new file mode 100644
index 0000000..b9d1baf
--- /dev/null
+++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/connectionstate.js
@@ -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;
diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/document.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/document.js
new file mode 100644
index 0000000..968ad1a
--- /dev/null
+++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/document.js
@@ -0,0 +1,2615 @@
+/*!
+ * Module dependencies.
+ */
+
+var EventEmitter = require('events').EventEmitter;
+var MongooseError = require('./error');
+var MixedSchema = require('./schema/mixed');
+var Schema = require('./schema');
+var ObjectExpectedError = require('./error/objectExpected');
+var StrictModeError = require('./error/strict');
+var ValidatorError = require('./schematype').ValidatorError;
+var VersionError = require('./error').VersionError;
+var utils = require('./utils');
+var clone = utils.clone;
+var isMongooseObject = utils.isMongooseObject;
+var inspect = require('util').inspect;
+var ValidationError = MongooseError.ValidationError;
+var InternalCache = require('./internal');
+var deepEqual = utils.deepEqual;
+var hooks = require('hooks-fixed');
+var PromiseProvider = require('./promise_provider');
+var DocumentArray;
+var MongooseArray;
+var Embedded;
+var flatten = require('./services/common').flatten;
+var mpath = require('mpath');
+
+/**
+ * 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, fields, skipId) {
+ this.$__ = new InternalCache;
+ this.$__.emitter = new EventEmitter();
+ this.isNew = true;
+ this.errors = undefined;
+
+ var schema = this.schema;
+
+ if (typeof fields === 'boolean') {
+ this.$__.strictMode = fields;
+ fields = undefined;
+ } else {
+ this.$__.strictMode = schema.options && schema.options.strict;
+ this.$__.selected = fields;
+ }
+
+ var required = schema.requiredPaths(true);
+ for (var i = 0; i < required.length; ++i) {
+ this.$__.activePaths.require(required[i]);
+ }
+
+ this.$__.emitter.setMaxListeners(0);
+ this._doc = this.$__buildDoc(obj, fields, skipId);
+
+ if (obj) {
+ if (obj instanceof Document) {
+ this.isNew = obj.isNew;
+ }
+ this.set(obj, undefined, true);
+ }
+
+ if (!schema.options.strict && obj) {
+ var _this = this,
+ keys = Object.keys(this._doc);
+
+ keys.forEach(function(key) {
+ if (!(key in schema.tree)) {
+ defineKey(key, null, _this);
+ }
+ });
+ }
+
+ this.$__registerHooksFromSchema();
+}
+
+/*!
+ * Document exposes the NodeJS event emitter API, so you can use
+ * `on`, `once`, etc.
+ */
+utils.each(
+ ['on', 'once', 'emit', 'listeners', 'removeListener', 'setMaxListeners',
+ 'removeAllListeners', 'addListener'],
+ function(emitterFn) {
+ Document.prototype[emitterFn] = function() {
+ return this.$__.emitter[emitterFn].apply(this.$__.emitter, arguments);
+ };
+ });
+
+Document.prototype.constructor = Document;
+
+/**
+ * The documents schema.
+ *
+ * @api public
+ * @property schema
+ */
+
+Document.prototype.schema;
+
+/**
+ * Boolean flag specifying if the document is new.
+ *
+ * @api public
+ * @property isNew
+ */
+
+Document.prototype.isNew;
+
+/**
+ * The string version of this documents _id.
+ *
+ * ####Note:
+ *
+ * This getter exists on all documents by default. The getter can be disabled by setting the `id` [option](/docs/guide.html#id) of its `Schema` to false at construction time.
+ *
+ * new Schema({ name: String }, { id: false });
+ *
+ * @api public
+ * @see Schema options /docs/guide.html#options
+ * @property id
+ */
+
+Document.prototype.id;
+
+/**
+ * Hash containing current validation errors.
+ *
+ * @api public
+ * @property errors
+ */
+
+Document.prototype.errors;
+
+/**
+ * Builds the default doc structure
+ *
+ * @param {Object} obj
+ * @param {Object} [fields]
+ * @param {Boolean} [skipId]
+ * @return {Object}
+ * @api private
+ * @method $__buildDoc
+ * @memberOf Document
+ */
+
+Document.prototype.$__buildDoc = function(obj, fields, skipId) {
+ var doc = {};
+ var exclude = null;
+ var keys;
+ var ki;
+ var _this = this;
+
+ // determine if this doc is a result of a query with
+ // excluded fields
+
+ if (fields && utils.getFunctionName(fields.constructor) === 'Object') {
+ keys = Object.keys(fields);
+ ki = keys.length;
+
+ if (ki === 1 && keys[0] === '_id') {
+ exclude = !!fields[keys[ki]];
+ } else {
+ while (ki--) {
+ if (keys[ki] !== '_id' &&
+ (!fields[keys[ki]] || typeof fields[keys[ki]] !== 'object')) {
+ exclude = !fields[keys[ki]];
+ break;
+ }
+ }
+ }
+ }
+
+ var paths = Object.keys(this.schema.paths);
+ var plen = paths.length;
+ var ii = 0;
+
+ var hasIncludedChildren = {};
+ if (exclude === false && fields) {
+ keys = Object.keys(fields);
+ for (var j = 0; j < keys.length; ++j) {
+ var parts = keys[j].split('.');
+ var c = [];
+ for (var k = 0; k < parts.length; ++k) {
+ c.push(parts[k]);
+ hasIncludedChildren[c.join('.')] = 1;
+ }
+ }
+ }
+
+ for (; ii < plen; ++ii) {
+ var p = paths[ii];
+
+ if (p === '_id') {
+ if (skipId) {
+ continue;
+ }
+ if (obj && '_id' in obj) {
+ continue;
+ }
+ }
+
+ var type = this.schema.paths[p];
+ var path = p.split('.');
+ var len = path.length;
+ var last = len - 1;
+ var curPath = '';
+ var doc_ = doc;
+ var i = 0;
+ var included = false;
+
+ for (; i < len; ++i) {
+ var piece = path[i],
+ def;
+
+ curPath += (!curPath.length ? '' : '.') + piece;
+
+ // support excluding intermediary levels
+ if (exclude === true) {
+ if (curPath in fields) {
+ break;
+ }
+ } else if (exclude === false && fields && !included) {
+ if (curPath in fields) {
+ included = true;
+ } else if (!hasIncludedChildren[curPath]) {
+ break;
+ }
+ }
+
+ if (i === last) {
+ if (fields && exclude !== null) {
+ if (exclude === true) {
+ // apply defaults to all non-excluded fields
+ if (p in fields) {
+ continue;
+ }
+
+ def = type.getDefault(_this, false);
+ if (typeof def !== 'undefined') {
+ doc_[piece] = def;
+ _this.$__.activePaths.default(p);
+ }
+ } else if (included) {
+ // selected field
+ def = type.getDefault(_this, false);
+ if (typeof def !== 'undefined') {
+ doc_[piece] = def;
+ _this.$__.activePaths.default(p);
+ }
+ }
+ } else {
+ def = type.getDefault(_this, false);
+ if (typeof def !== 'undefined') {
+ doc_[piece] = def;
+ _this.$__.activePaths.default(p);
+ }
+ }
+ } else {
+ doc_ = doc_[piece] || (doc_[piece] = {});
+ }
+ }
+ }
+
+ return doc;
+};
+
+/**
+ * Initializes the document without setters or marking anything modified.
+ *
+ * Called internally after a document is returned from mongodb.
+ *
+ * @param {Object} doc document returned by mongo
+ * @param {Function} fn callback
+ * @api public
+ */
+
+Document.prototype.init = function(doc, opts, fn) {
+ // do not prefix this method with $__ since its
+ // used by public hooks
+
+ if (typeof opts === 'function') {
+ fn = opts;
+ opts = null;
+ }
+
+ this.isNew = false;
+
+ // handle docs with populated paths
+ // If doc._id is not null or undefined
+ if (doc._id !== null && doc._id !== undefined &&
+ opts && opts.populated && opts.populated.length) {
+ var id = String(doc._id);
+ for (var i = 0; i < opts.populated.length; ++i) {
+ var item = opts.populated[i];
+ if (item.isVirtual) {
+ this.populated(item.path, utils.getValue(item.path, doc), item);
+ } else {
+ this.populated(item.path, item._docs[id], item);
+ }
+ }
+ }
+
+ init(this, doc, this._doc);
+ this.$__storeShard();
+
+ this.emit('init', this);
+ if (fn) {
+ fn(null);
+ }
+ return this;
+};
+
+/*!
+ * Init helper.
+ *
+ * @param {Object} self document instance
+ * @param {Object} obj raw mongodb doc
+ * @param {Object} doc object we are initializing
+ * @api private
+ */
+
+function init(self, obj, doc, prefix) {
+ prefix = prefix || '';
+
+ var keys = Object.keys(obj);
+ var len = keys.length;
+ var schema;
+ var path;
+ var i;
+ var index = 0;
+
+ if (self.schema.options.retainKeyOrder) {
+ while (index < len) {
+ _init(index++);
+ }
+ } else {
+ while (len--) {
+ _init(len);
+ }
+ }
+
+ function _init(index) {
+ i = keys[index];
+ path = prefix + i;
+ schema = self.schema.path(path);
+
+ if (!schema && utils.isObject(obj[i]) &&
+ (!obj[i].constructor || utils.getFunctionName(obj[i].constructor) === 'Object')) {
+ // assume nested object
+ if (!doc[i]) {
+ doc[i] = {};
+ }
+ init(self, obj[i], doc[i], path + '.');
+ } else {
+ if (obj[i] === null) {
+ doc[i] = null;
+ } else if (obj[i] !== undefined) {
+ if (schema) {
+ try {
+ doc[i] = schema.cast(obj[i], self, true);
+ } catch (e) {
+ self.invalidate(e.path, new ValidatorError({
+ path: e.path,
+ message: e.message,
+ type: 'cast',
+ value: e.value
+ }));
+ }
+ } else {
+ doc[i] = obj[i];
+ }
+ }
+ // mark as hydrated
+ if (!self.isModified(path)) {
+ self.$__.activePaths.init(path);
+ }
+ }
+ }
+}
+
+/**
+ * Stores the current values of the shard keys.
+ *
+ * ####Note:
+ *
+ * _Shard key values do not / are not allowed to change._
+ *
+ * @api private
+ * @method $__storeShard
+ * @memberOf Document
+ */
+
+Document.prototype.$__storeShard = function() {
+ // backwards compat
+ var key = this.schema.options.shardKey || this.schema.options.shardkey;
+ if (!(key && utils.getFunctionName(key.constructor) === 'Object')) {
+ return;
+ }
+
+ var orig = this.$__.shardval = {},
+ paths = Object.keys(key),
+ len = paths.length,
+ val;
+
+ for (var i = 0; i < len; ++i) {
+ val = this.getValue(paths[i]);
+ if (isMongooseObject(val)) {
+ orig[paths[i]] = val.toObject({depopulate: true, _isNested: true});
+ } else if (val !== null && val !== undefined && val.valueOf &&
+ // Explicitly don't take value of dates
+ (!val.constructor || utils.getFunctionName(val.constructor) !== 'Date')) {
+ orig[paths[i]] = val.valueOf();
+ } else {
+ orig[paths[i]] = val;
+ }
+ }
+};
+
+/*!
+ * Set up middleware support
+ */
+
+for (var k in hooks) {
+ if (k === 'pre' || k === 'post') {
+ Document.prototype['$' + k] = Document['$' + k] = hooks[k];
+ } else {
+ Document.prototype[k] = Document[k] = hooks[k];
+ }
+}
+
+/**
+ * Sends an update command with this document `_id` as the query selector.
+ *
+ * ####Example:
+ *
+ * weirdCar.update({$inc: {wheels:1}}, { w: 1 }, callback);
+ *
+ * ####Valid options:
+ *
+ * - same as in [Model.update](#model_Model.update)
+ *
+ * @see Model.update #model_Model.update
+ * @param {Object} doc
+ * @param {Object} options
+ * @param {Function} callback
+ * @return {Query}
+ * @api public
+ */
+
+Document.prototype.update = function update() {
+ var args = utils.args(arguments);
+ args.unshift({_id: this._id});
+ return this.constructor.update.apply(this.constructor, args);
+};
+
+/**
+ * Sets the value of a path, or many paths.
+ *
+ * ####Example:
+ *
+ * // path, value
+ * doc.set(path, value)
+ *
+ * // object
+ * doc.set({
+ * path : value
+ * , path2 : {
+ * path : value
+ * }
+ * })
+ *
+ * // on-the-fly cast to number
+ * doc.set(path, value, Number)
+ *
+ * // on-the-fly cast to string
+ * doc.set(path, value, String)
+ *
+ * // changing strict mode behavior
+ * doc.set(path, value, { strict: false });
+ *
+ * @param {String|Object} path path or object of key/vals to set
+ * @param {Any} val the value to set
+ * @param {Schema|String|Number|Buffer|*} [type] optionally specify a type for "on-the-fly" attributes
+ * @param {Object} [options] optionally specify options that modify the behavior of the set
+ * @api public
+ */
+
+Document.prototype.set = function(path, val, type, options) {
+ if (type && utils.getFunctionName(type.constructor) === 'Object') {
+ options = type;
+ type = undefined;
+ }
+
+ var merge = options && options.merge,
+ adhoc = type && type !== true,
+ constructing = type === true,
+ adhocs;
+
+ var strict = options && 'strict' in options
+ ? options.strict
+ : this.$__.strictMode;
+
+ if (adhoc) {
+ adhocs = this.$__.adhocPaths || (this.$__.adhocPaths = {});
+ adhocs[path] = Schema.interpretAsType(path, type, this.schema.options);
+ }
+
+ if (typeof path !== 'string') {
+ // new Document({ key: val })
+
+ if (path === null || path === void 0) {
+ var _ = path;
+ path = val;
+ val = _;
+ } else {
+ var prefix = val
+ ? val + '.'
+ : '';
+
+ if (path instanceof Document) {
+ if (path.$__isNested) {
+ path = path.toObject();
+ } else {
+ path = path._doc;
+ }
+ }
+
+ var keys = Object.keys(path);
+ var len = keys.length;
+ var i = 0;
+ var pathtype;
+ var key;
+
+ if (len === 0 && !this.schema.options.minimize) {
+ if (val) {
+ this.set(val, {});
+ }
+ return this;
+ }
+
+ if (this.schema.options.retainKeyOrder) {
+ while (i < len) {
+ _handleIndex.call(this, i++);
+ }
+ } else {
+ while (len--) {
+ _handleIndex.call(this, len);
+ }
+ }
+
+ return this;
+ }
+ }
+
+ function _handleIndex(i) {
+ key = keys[i];
+ var pathName = prefix + key;
+ pathtype = this.schema.pathType(pathName);
+
+ if (path[key] !== null
+ && path[key] !== void 0
+ // need to know if plain object - no Buffer, ObjectId, ref, etc
+ && utils.isObject(path[key])
+ && (!path[key].constructor || utils.getFunctionName(path[key].constructor) === 'Object')
+ && pathtype !== 'virtual'
+ && pathtype !== 'real'
+ && !(this.$__path(pathName) instanceof MixedSchema)
+ && !(this.schema.paths[pathName] &&
+ this.schema.paths[pathName].options &&
+ this.schema.paths[pathName].options.ref)) {
+ this.set(path[key], prefix + key, constructing);
+ } else if (strict) {
+ // Don't overwrite defaults with undefined keys (gh-3981)
+ if (constructing && path[key] === void 0 &&
+ this.get(key) !== void 0) {
+ return;
+ }
+
+ if (pathtype === 'real' || pathtype === 'virtual') {
+ // Check for setting single embedded schema to document (gh-3535)
+ if (this.schema.paths[pathName] &&
+ this.schema.paths[pathName].$isSingleNested &&
+ path[key] instanceof Document) {
+ path[key] = path[key].toObject({virtuals: false});
+ }
+ this.set(prefix + key, path[key], constructing);
+ } else if (pathtype === 'nested' && path[key] instanceof Document) {
+ this.set(prefix + key,
+ path[key].toObject({transform: false}), constructing);
+ } else if (strict === 'throw') {
+ if (pathtype === 'nested') {
+ throw new ObjectExpectedError(key, path[key]);
+ } else {
+ throw new StrictModeError(key);
+ }
+ }
+ } else if (path[key] !== void 0) {
+ this.set(prefix + key, path[key], constructing);
+ }
+ }
+
+ // ensure _strict is honored for obj props
+ // docschema = new Schema({ path: { nest: 'string' }})
+ // doc.set('path', obj);
+ var pathType = this.schema.pathType(path);
+ if (pathType === 'nested' && val) {
+ if (utils.isObject(val) &&
+ (!val.constructor || utils.getFunctionName(val.constructor) === 'Object')) {
+ if (!merge) {
+ this.setValue(path, null);
+ cleanModifiedSubpaths(this, path);
+ }
+
+ if (Object.keys(val).length === 0) {
+ this.setValue(path, {});
+ this.markModified(path);
+ cleanModifiedSubpaths(this, path);
+ } else {
+ this.set(val, path, constructing);
+ }
+ return this;
+ }
+ this.invalidate(path, new MongooseError.CastError('Object', val, path));
+ return this;
+ }
+
+ var schema;
+ var parts = path.split('.');
+
+ if (pathType === 'adhocOrUndefined' && strict) {
+ // check for roots that are Mixed types
+ var mixed;
+
+ for (i = 0; i < parts.length; ++i) {
+ var subpath = parts.slice(0, i + 1).join('.');
+ schema = this.schema.path(subpath);
+ if (schema instanceof MixedSchema) {
+ // allow changes to sub paths of mixed types
+ mixed = true;
+ break;
+ }
+
+ // If path is underneath a virtual, bypass everything and just set it.
+ if (i + 1 < parts.length && this.schema.pathType(subpath) === 'virtual') {
+ mpath.set(path, val, this);
+ return this;
+ }
+ }
+
+ if (!mixed) {
+ if (strict === 'throw') {
+ throw new StrictModeError(path);
+ }
+ return this;
+ }
+ } else if (pathType === 'virtual') {
+ schema = this.schema.virtualpath(path);
+ schema.applySetters(val, this);
+ return this;
+ } else {
+ schema = this.$__path(path);
+ }
+
+ var pathToMark;
+
+ // When using the $set operator the path to the field must already exist.
+ // Else mongodb throws: "LEFT_SUBFIELD only supports Object"
+
+ if (parts.length <= 1) {
+ pathToMark = path;
+ } else {
+ for (i = 0; i < parts.length; ++i) {
+ subpath = parts.slice(0, i + 1).join('.');
+ if (this.isDirectModified(subpath) // earlier prefixes that are already
+ // marked as dirty have precedence
+ || this.get(subpath) === null) {
+ pathToMark = subpath;
+ break;
+ }
+ }
+
+ if (!pathToMark) {
+ pathToMark = path;
+ }
+ }
+
+ // if this doc is being constructed we should not trigger getters
+ var priorVal = constructing
+ ? undefined
+ : this.getValue(path);
+
+ if (!schema) {
+ this.$__set(pathToMark, path, constructing, parts, schema, val, priorVal);
+ return this;
+ }
+
+ var shouldSet = true;
+ try {
+ // If the user is trying to set a ref path to a document with
+ // the correct model name, treat it as populated
+ var didPopulate = false;
+ if (schema.options &&
+ schema.options.ref &&
+ val instanceof Document &&
+ schema.options.ref === val.constructor.modelName) {
+ if (this.ownerDocument) {
+ this.ownerDocument().populated(this.$__fullPath(path),
+ val._id, {model: val.constructor});
+ } else {
+ this.populated(path, val._id, {model: val.constructor});
+ }
+ didPopulate = true;
+ }
+
+ var popOpts;
+ if (schema.options &&
+ Array.isArray(schema.options.type) &&
+ schema.options.type.length &&
+ schema.options.type[0].ref &&
+ Array.isArray(val) &&
+ val.length > 0 &&
+ val[0] instanceof Document &&
+ val[0].constructor.modelName &&
+ schema.options.type[0].ref === val[0].constructor.modelName) {
+ if (this.ownerDocument) {
+ popOpts = { model: val[0].constructor };
+ this.ownerDocument().populated(this.$__fullPath(path),
+ val.map(function(v) { return v._id; }), popOpts);
+ } else {
+ popOpts = { model: val[0].constructor };
+ this.populated(path, val.map(function(v) { return v._id; }), popOpts);
+ }
+ didPopulate = true;
+ }
+ val = schema.applySetters(val, this, false, priorVal);
+
+ if (!didPopulate && this.$__.populated) {
+ delete this.$__.populated[path];
+ }
+
+ this.$markValid(path);
+ } catch (e) {
+ this.invalidate(path,
+ new MongooseError.CastError(schema.instance, val, path, e));
+ shouldSet = false;
+ }
+
+ if (shouldSet) {
+ this.$__set(pathToMark, path, constructing, parts, schema, val, priorVal);
+ }
+
+ if (schema.$isSingleNested && this.isDirectModified(path)) {
+ cleanModifiedSubpaths(this, path);
+ }
+
+ return this;
+};
+
+/*!
+ * ignore
+ */
+
+function cleanModifiedSubpaths(doc, path) {
+ var _modifiedPaths = Object.keys(doc.$__.activePaths.states.modify);
+ var _numModifiedPaths = _modifiedPaths.length;
+ for (var j = 0; j < _numModifiedPaths; ++j) {
+ if (_modifiedPaths[j].indexOf(path + '.') === 0) {
+ delete doc.$__.activePaths.states.modify[_modifiedPaths[j]];
+ }
+ }
+}
+
+/**
+ * Determine if we should mark this change as modified.
+ *
+ * @return {Boolean}
+ * @api private
+ * @method $__shouldModify
+ * @memberOf Document
+ */
+
+Document.prototype.$__shouldModify = function(pathToMark, path, constructing, parts, schema, val, priorVal) {
+ if (this.isNew) {
+ return true;
+ }
+
+ if (undefined === val && !this.isSelected(path)) {
+ // when a path is not selected in a query, its initial
+ // value will be undefined.
+ return true;
+ }
+
+ if (undefined === val && path in this.$__.activePaths.states.default) {
+ // we're just unsetting the default value which was never saved
+ return false;
+ }
+
+ // gh-3992: if setting a populated field to a doc, don't mark modified
+ // if they have the same _id
+ if (this.populated(path) &&
+ val instanceof Document &&
+ deepEqual(val._id, priorVal)) {
+ return false;
+ }
+
+ if (!deepEqual(val, priorVal || this.get(path))) {
+ return true;
+ }
+
+ if (!constructing &&
+ val !== null &&
+ val !== undefined &&
+ path in this.$__.activePaths.states.default &&
+ deepEqual(val, schema.getDefault(this, constructing))) {
+ // a path with a default was $unset on the server
+ // and the user is setting it to the same value again
+ return true;
+ }
+ return false;
+};
+
+/**
+ * Handles the actual setting of the value and marking the path modified if appropriate.
+ *
+ * @api private
+ * @method $__set
+ * @memberOf Document
+ */
+
+Document.prototype.$__set = function(pathToMark, path, constructing, parts, schema, val, priorVal) {
+ Embedded = Embedded || require('./types/embedded');
+
+ var shouldModify = this.$__shouldModify(pathToMark, path, constructing, parts,
+ schema, val, priorVal);
+ var _this = this;
+
+ if (shouldModify) {
+ this.markModified(pathToMark, val);
+
+ // handle directly setting arrays (gh-1126)
+ MongooseArray || (MongooseArray = require('./types/array'));
+ if (val && val.isMongooseArray) {
+ val._registerAtomic('$set', val);
+
+ // Small hack for gh-1638: if we're overwriting the entire array, ignore
+ // paths that were modified before the array overwrite
+ this.$__.activePaths.forEach(function(modifiedPath) {
+ if (modifiedPath.indexOf(path + '.') === 0) {
+ _this.$__.activePaths.ignore(modifiedPath);
+ }
+ });
+ }
+ }
+
+ var obj = this._doc;
+ var i = 0;
+ var l = parts.length;
+ var cur = '';
+
+ for (; i < l; i++) {
+ var next = i + 1;
+ var last = next === l;
+ cur += (cur ? '.' + parts[i] : parts[i]);
+
+ if (last) {
+ obj[parts[i]] = val;
+ } else {
+ if (obj[parts[i]] && utils.getFunctionName(obj[parts[i]].constructor) === 'Object') {
+ obj = obj[parts[i]];
+ } else if (obj[parts[i]] && obj[parts[i]] instanceof Embedded) {
+ obj = obj[parts[i]];
+ } else if (obj[parts[i]] && obj[parts[i]].$isSingleNested) {
+ obj = obj[parts[i]];
+ } else if (obj[parts[i]] && Array.isArray(obj[parts[i]])) {
+ obj = obj[parts[i]];
+ } else {
+ this.set(cur, {});
+ obj = obj[parts[i]];
+ }
+ }
+ }
+};
+
+/**
+ * Gets a raw value from a path (no getters)
+ *
+ * @param {String} path
+ * @api private
+ */
+
+Document.prototype.getValue = function(path) {
+ return utils.getValue(path, this._doc);
+};
+
+/**
+ * Sets a raw value for a path (no casting, setters, transformations)
+ *
+ * @param {String} path
+ * @param {Object} value
+ * @api private
+ */
+
+Document.prototype.setValue = function(path, val) {
+ utils.setValue(path, val, this._doc);
+ return this;
+};
+
+/**
+ * Returns the value of a path.
+ *
+ * ####Example
+ *
+ * // path
+ * doc.get('age') // 47
+ *
+ * // dynamic casting to a string
+ * doc.get('age', String) // "47"
+ *
+ * @param {String} path
+ * @param {Schema|String|Number|Buffer|*} [type] optionally specify a type for on-the-fly attributes
+ * @api public
+ */
+
+Document.prototype.get = function(path, type) {
+ var adhoc;
+ if (type) {
+ adhoc = Schema.interpretAsType(path, type, this.schema.options);
+ }
+
+ var schema = this.$__path(path) || this.schema.virtualpath(path),
+ pieces = path.split('.'),
+ obj = this._doc;
+
+ for (var i = 0, l = pieces.length; i < l; i++) {
+ obj = obj === null || obj === void 0
+ ? undefined
+ : obj[pieces[i]];
+ }
+
+ if (adhoc) {
+ obj = adhoc.cast(obj);
+ }
+
+ // Check if this path is populated - don't apply getters if it is,
+ // because otherwise its a nested object. See gh-3357
+ if (schema && !this.populated(path)) {
+ obj = schema.applyGetters(obj, this);
+ }
+
+ return obj;
+};
+
+/**
+ * Returns the schematype for the given `path`.
+ *
+ * @param {String} path
+ * @api private
+ * @method $__path
+ * @memberOf Document
+ */
+
+Document.prototype.$__path = function(path) {
+ var adhocs = this.$__.adhocPaths,
+ adhocType = adhocs && adhocs[path];
+
+ if (adhocType) {
+ return adhocType;
+ }
+ return this.schema.path(path);
+};
+
+/**
+ * Marks the path as having pending changes to write to the db.
+ *
+ * _Very helpful when using [Mixed](./schematypes.html#mixed) types._
+ *
+ * ####Example:
+ *
+ * doc.mixed.type = 'changed';
+ * doc.markModified('mixed.type');
+ * doc.save() // changes to mixed.type are now persisted
+ *
+ * @param {String} path the path to mark modified
+ * @api public
+ */
+
+Document.prototype.markModified = function(path) {
+ this.$__.activePaths.modify(path);
+};
+
+/**
+ * Clears the modified state on the specified path.
+ *
+ * ####Example:
+ *
+ * doc.foo = 'bar';
+ * doc.unmarkModified('foo');
+ * doc.save() // changes to foo will not be persisted
+ *
+ * @param {String} path the path to unmark modified
+ * @api public
+ */
+
+Document.prototype.unmarkModified = function(path) {
+ this.$__.activePaths.init(path);
+};
+
+/**
+ * Don't run validation on this path or persist changes to this path.
+ *
+ * ####Example:
+ *
+ * doc.foo = null;
+ * doc.$ignore('foo');
+ * doc.save() // changes to foo will not be persisted and validators won't be run
+ *
+ * @param {String} path the path to ignore
+ * @api public
+ */
+
+Document.prototype.$ignore = function(path) {
+ this.$__.activePaths.ignore(path);
+};
+
+/**
+ * Returns the list of paths that have been modified.
+ *
+ * @return {Array}
+ * @api public
+ */
+
+Document.prototype.modifiedPaths = function() {
+ var directModifiedPaths = Object.keys(this.$__.activePaths.states.modify);
+ return directModifiedPaths.reduce(function(list, path) {
+ var parts = path.split('.');
+ return list.concat(parts.reduce(function(chains, part, i) {
+ return chains.concat(parts.slice(0, i).concat(part).join('.'));
+ }, []).filter(function(chain) {
+ return (list.indexOf(chain) === -1);
+ }));
+ }, []);
+};
+
+/**
+ * Returns true if this document was modified, else false.
+ *
+ * If `path` is given, checks if a path or any full path containing `path` as part of its path chain has been modified.
+ *
+ * ####Example
+ *
+ * doc.set('documents.0.title', 'changed');
+ * doc.isModified() // true
+ * doc.isModified('documents') // true
+ * doc.isModified('documents.0.title') // true
+ * doc.isModified('documents otherProp') // true
+ * doc.isDirectModified('documents') // false
+ *
+ * @param {String} [path] optional
+ * @return {Boolean}
+ * @api public
+ */
+
+Document.prototype.isModified = function(paths) {
+ if (paths) {
+ if (!Array.isArray(paths)) {
+ paths = paths.split(' ');
+ }
+ var modified = this.modifiedPaths();
+ var directModifiedPaths = Object.keys(this.$__.activePaths.states.modify);
+ var isModifiedChild = paths.some(function(path) {
+ return !!~modified.indexOf(path);
+ });
+ return isModifiedChild || paths.some(function(path) {
+ return directModifiedPaths.some(function(mod) {
+ return mod === path || path.indexOf(mod + '.') === 0;
+ });
+ });
+ }
+ return this.$__.activePaths.some('modify');
+};
+
+/**
+ * Checks if a path is set to its default.
+ *
+ * ####Example
+ *
+ * MyModel = mongoose.model('test', { name: { type: String, default: 'Val '} });
+ * var m = new MyModel();
+ * m.$isDefault('name'); // true
+ *
+ * @param {String} [path]
+ * @return {Boolean}
+ * @method $isDefault
+ * @api public
+ */
+
+Document.prototype.$isDefault = function(path) {
+ return (path in this.$__.activePaths.states.default);
+};
+
+/**
+ * Returns true if `path` was directly set and modified, else false.
+ *
+ * ####Example
+ *
+ * doc.set('documents.0.title', 'changed');
+ * doc.isDirectModified('documents.0.title') // true
+ * doc.isDirectModified('documents') // false
+ *
+ * @param {String} path
+ * @return {Boolean}
+ * @api public
+ */
+
+Document.prototype.isDirectModified = function(path) {
+ return (path in this.$__.activePaths.states.modify);
+};
+
+/**
+ * Checks if `path` was initialized.
+ *
+ * @param {String} path
+ * @return {Boolean}
+ * @api public
+ */
+
+Document.prototype.isInit = function(path) {
+ return (path in this.$__.activePaths.states.init);
+};
+
+/**
+ * Checks if `path` was selected in the source query which initialized this document.
+ *
+ * ####Example
+ *
+ * Thing.findOne().select('name').exec(function (err, doc) {
+ * doc.isSelected('name') // true
+ * doc.isSelected('age') // false
+ * })
+ *
+ * @param {String} path
+ * @return {Boolean}
+ * @api public
+ */
+
+Document.prototype.isSelected = function isSelected(path) {
+ if (this.$__.selected) {
+ if (path === '_id') {
+ return this.$__.selected._id !== 0;
+ }
+
+ var paths = Object.keys(this.$__.selected),
+ i = paths.length,
+ inclusive = false,
+ cur;
+
+ if (i === 1 && paths[0] === '_id') {
+ // only _id was selected.
+ return this.$__.selected._id === 0;
+ }
+
+ while (i--) {
+ cur = paths[i];
+ if (cur === '_id') {
+ continue;
+ }
+ inclusive = !!this.$__.selected[cur];
+ break;
+ }
+
+ if (path in this.$__.selected) {
+ return inclusive;
+ }
+
+ i = paths.length;
+ var pathDot = path + '.';
+
+ while (i--) {
+ cur = paths[i];
+ if (cur === '_id') {
+ continue;
+ }
+
+ if (cur.indexOf(pathDot) === 0) {
+ return inclusive;
+ }
+
+ if (pathDot.indexOf(cur + '.') === 0) {
+ return inclusive;
+ }
+ }
+
+ return !inclusive;
+ }
+
+ return true;
+};
+
+/**
+ * Executes registered validation rules for this document.
+ *
+ * ####Note:
+ *
+ * This method is called `pre` save and if a validation rule is violated, [save](#model_Model-save) is aborted and the error is returned to your `callback`.
+ *
+ * ####Example:
+ *
+ * doc.validate(function (err) {
+ * if (err) handleError(err);
+ * else // validation passed
+ * });
+ *
+ * @param {Object} optional options internal options
+ * @param {Function} callback optional callback called after validation completes, passing an error if one occurred
+ * @return {Promise} Promise
+ * @api public
+ */
+
+Document.prototype.validate = function(options, callback) {
+ if (typeof options === 'function') {
+ callback = options;
+ options = null;
+ }
+
+ this.$__validate(callback);
+};
+
+/*!
+ * ignore
+ */
+
+function _getPathsToValidate(doc) {
+ // only validate required fields when necessary
+ var paths = Object.keys(doc.$__.activePaths.states.require).filter(function(path) {
+ if (!doc.isSelected(path) && !doc.isModified(path)) {
+ return false;
+ }
+ var p = doc.schema.path(path);
+ if (typeof p.originalRequiredValue === 'function') {
+ return p.originalRequiredValue.call(doc);
+ }
+ return true;
+ });
+
+ paths = paths.concat(Object.keys(doc.$__.activePaths.states.init));
+ paths = paths.concat(Object.keys(doc.$__.activePaths.states.modify));
+ paths = paths.concat(Object.keys(doc.$__.activePaths.states.default));
+
+ // gh-661: if a whole array is modified, make sure to run validation on all
+ // the children as well
+ for (var i = 0; i < paths.length; ++i) {
+ var path = paths[i];
+ var val = doc.getValue(path);
+ if (val && val.isMongooseArray && !Buffer.isBuffer(val) && !val.isMongooseDocumentArray) {
+ var numElements = val.length;
+ for (var j = 0; j < numElements; ++j) {
+ paths.push(path + '.' + j);
+ }
+ }
+ }
+
+ var flattenOptions = { skipArrays: true };
+ for (i = 0; i < paths.length; ++i) {
+ var pathToCheck = paths[i];
+ if (doc.schema.nested[pathToCheck]) {
+ var _v = doc.getValue(pathToCheck);
+ if (isMongooseObject(_v)) {
+ _v = _v.toObject({ transform: false });
+ }
+ var flat = flatten(_v, '', flattenOptions);
+ var _subpaths = Object.keys(flat).map(function(p) {
+ return pathToCheck + '.' + p;
+ });
+ paths = paths.concat(_subpaths);
+ }
+ }
+
+ return paths;
+}
+
+/*!
+ * ignore
+ */
+
+Document.prototype.$__validate = function(callback) {
+ var _this = this;
+ var _complete = function() {
+ var err = _this.$__.validationError;
+ _this.$__.validationError = undefined;
+ _this.emit('validate', _this);
+ if (err) {
+ for (var key in err.errors) {
+ // Make sure cast errors persist
+ if (!_this.__parent && err.errors[key] instanceof MongooseError.CastError) {
+ _this.invalidate(key, err.errors[key]);
+ }
+ }
+
+ return err;
+ }
+ };
+
+ // only validate required fields when necessary
+ var paths = _getPathsToValidate(this);
+
+ if (paths.length === 0) {
+ process.nextTick(function() {
+ var err = _complete();
+ if (err) {
+ callback(err);
+ return;
+ }
+ callback();
+ });
+ }
+
+ var validating = {},
+ total = 0;
+
+ var complete = function() {
+ var err = _complete();
+ if (err) {
+ callback(err);
+ return;
+ }
+ callback();
+ };
+
+ var validatePath = function(path) {
+ if (validating[path]) {
+ return;
+ }
+
+ validating[path] = true;
+ total++;
+
+ process.nextTick(function() {
+ var p = _this.schema.path(path);
+ if (!p) {
+ return --total || complete();
+ }
+
+ // If user marked as invalid or there was a cast error, don't validate
+ if (!_this.$isValid(path)) {
+ --total || complete();
+ return;
+ }
+
+ var val = _this.getValue(path);
+ p.doValidate(val, function(err) {
+ if (err) {
+ _this.invalidate(path, err, undefined, true);
+ }
+ --total || complete();
+ }, _this);
+ });
+ };
+
+ paths.forEach(validatePath);
+};
+
+/**
+ * Executes registered validation rules (skipping asynchronous validators) for this document.
+ *
+ * ####Note:
+ *
+ * This method is useful if you need synchronous validation.
+ *
+ * ####Example:
+ *
+ * var err = doc.validateSync();
+ * if ( err ){
+ * handleError( err );
+ * } else {
+ * // validation passed
+ * }
+ *
+ * @param {Array|string} pathsToValidate only validate the given paths
+ * @return {MongooseError|undefined} MongooseError if there are errors during validation, or undefined if there is no error.
+ * @api public
+ */
+
+Document.prototype.validateSync = function(pathsToValidate) {
+ var _this = this;
+
+ if (typeof pathsToValidate === 'string') {
+ pathsToValidate = pathsToValidate.split(' ');
+ }
+
+ // only validate required fields when necessary
+ var paths = _getPathsToValidate(this);
+
+ if (pathsToValidate && pathsToValidate.length) {
+ var tmp = [];
+ for (var i = 0; i < paths.length; ++i) {
+ if (pathsToValidate.indexOf(paths[i]) !== -1) {
+ tmp.push(paths[i]);
+ }
+ }
+ paths = tmp;
+ }
+
+ var validating = {};
+
+ paths.forEach(function(path) {
+ if (validating[path]) {
+ return;
+ }
+
+ validating[path] = true;
+
+ var p = _this.schema.path(path);
+ if (!p) {
+ return;
+ }
+ if (!_this.$isValid(path)) {
+ return;
+ }
+
+ var val = _this.getValue(path);
+ var err = p.doValidateSync(val, _this);
+ if (err) {
+ _this.invalidate(path, err, undefined, true);
+ }
+ });
+
+ var err = _this.$__.validationError;
+ _this.$__.validationError = undefined;
+ _this.emit('validate', _this);
+
+ if (err) {
+ for (var key in err.errors) {
+ // Make sure cast errors persist
+ if (err.errors[key] instanceof MongooseError.CastError) {
+ _this.invalidate(key, err.errors[key]);
+ }
+ }
+ }
+
+ return err;
+};
+
+/**
+ * Marks a path as invalid, causing validation to fail.
+ *
+ * The `errorMsg` argument will become the message of the `ValidationError`.
+ *
+ * The `value` argument (if passed) will be available through the `ValidationError.value` property.
+ *
+ * doc.invalidate('size', 'must be less than 20', 14);
+
+ * doc.validate(function (err) {
+ * console.log(err)
+ * // prints
+ * { message: 'Validation failed',
+ * name: 'ValidationError',
+ * errors:
+ * { size:
+ * { message: 'must be less than 20',
+ * name: 'ValidatorError',
+ * path: 'size',
+ * type: 'user defined',
+ * value: 14 } } }
+ * })
+ *
+ * @param {String} path the field to invalidate
+ * @param {String|Error} errorMsg the error which states the reason `path` was invalid
+ * @param {Object|String|Number|any} value optional invalid value
+ * @param {String} [kind] optional `kind` property for the error
+ * @return {ValidationError} the current ValidationError, with all currently invalidated paths
+ * @api public
+ */
+
+Document.prototype.invalidate = function(path, err, val, kind) {
+ if (!this.$__.validationError) {
+ this.$__.validationError = new ValidationError(this);
+ }
+
+ if (this.$__.validationError.errors[path]) {
+ return;
+ }
+
+ if (!err || typeof err === 'string') {
+ err = new ValidatorError({
+ path: path,
+ message: err,
+ type: kind || 'user defined',
+ value: val
+ });
+ }
+
+ if (this.$__.validationError === err) {
+ return this.$__.validationError;
+ }
+
+ this.$__.validationError.errors[path] = err;
+ return this.$__.validationError;
+};
+
+/**
+ * Marks a path as valid, removing existing validation errors.
+ *
+ * @param {String} path the field to mark as valid
+ * @api private
+ * @method $markValid
+ * @receiver Document
+ */
+
+Document.prototype.$markValid = function(path) {
+ if (!this.$__.validationError || !this.$__.validationError.errors[path]) {
+ return;
+ }
+
+ delete this.$__.validationError.errors[path];
+ if (Object.keys(this.$__.validationError.errors).length === 0) {
+ this.$__.validationError = null;
+ }
+};
+
+/**
+ * Checks if a path is invalid
+ *
+ * @param {String} path the field to check
+ * @method $isValid
+ * @api private
+ * @receiver Document
+ */
+
+Document.prototype.$isValid = function(path) {
+ return !this.$__.validationError || !this.$__.validationError.errors[path];
+};
+
+/**
+ * Resets the internal modified state of this document.
+ *
+ * @api private
+ * @return {Document}
+ * @method $__reset
+ * @memberOf Document
+ */
+
+Document.prototype.$__reset = function reset() {
+ var _this = this;
+ DocumentArray || (DocumentArray = require('./types/documentarray'));
+
+ this.$__.activePaths
+ .map('init', 'modify', function(i) {
+ return _this.getValue(i);
+ })
+ .filter(function(val) {
+ return val && val instanceof Array && val.isMongooseDocumentArray && val.length;
+ })
+ .forEach(function(array) {
+ var i = array.length;
+ while (i--) {
+ var doc = array[i];
+ if (!doc) {
+ continue;
+ }
+ doc.$__reset();
+ }
+ });
+
+ // clear atomics
+ this.$__dirty().forEach(function(dirt) {
+ var type = dirt.value;
+ if (type && type._atomics) {
+ type._atomics = {};
+ }
+ });
+
+ // Clear 'dirty' cache
+ this.$__.activePaths.clear('modify');
+ this.$__.activePaths.clear('default');
+ this.$__.validationError = undefined;
+ this.errors = undefined;
+ _this = this;
+ this.schema.requiredPaths().forEach(function(path) {
+ _this.$__.activePaths.require(path);
+ });
+
+ return this;
+};
+
+/**
+ * Returns this documents dirty paths / vals.
+ *
+ * @api private
+ * @method $__dirty
+ * @memberOf Document
+ */
+
+Document.prototype.$__dirty = function() {
+ var _this = this;
+
+ var all = this.$__.activePaths.map('modify', function(path) {
+ return {
+ path: path,
+ value: _this.getValue(path),
+ schema: _this.$__path(path)
+ };
+ });
+
+ // gh-2558: if we had to set a default and the value is not undefined,
+ // we have to save as well
+ all = all.concat(this.$__.activePaths.map('default', function(path) {
+ if (path === '_id' || !_this.getValue(path)) {
+ return;
+ }
+ return {
+ path: path,
+ value: _this.getValue(path),
+ schema: _this.$__path(path)
+ };
+ }));
+
+ // Sort dirty paths in a flat hierarchy.
+ all.sort(function(a, b) {
+ return (a.path < b.path ? -1 : (a.path > b.path ? 1 : 0));
+ });
+
+ // Ignore "foo.a" if "foo" is dirty already.
+ var minimal = [],
+ lastPath,
+ top;
+
+ all.forEach(function(item) {
+ if (!item) {
+ return;
+ }
+ if (item.path.indexOf(lastPath) !== 0) {
+ lastPath = item.path + '.';
+ minimal.push(item);
+ top = item;
+ } else {
+ // special case for top level MongooseArrays
+ if (top.value && top.value._atomics && top.value.hasAtomics()) {
+ // the `top` array itself and a sub path of `top` are being modified.
+ // the only way to honor all of both modifications is through a $set
+ // of entire array.
+ top.value._atomics = {};
+ top.value._atomics.$set = top.value;
+ }
+ }
+ });
+
+ top = lastPath = null;
+ return minimal;
+};
+
+/*!
+ * Compiles schemas.
+ */
+
+function compile(tree, proto, prefix, options) {
+ var keys = Object.keys(tree),
+ i = keys.length,
+ limb,
+ key;
+
+ while (i--) {
+ key = keys[i];
+ limb = tree[key];
+
+ defineKey(key,
+ ((utils.getFunctionName(limb.constructor) === 'Object'
+ && Object.keys(limb).length)
+ && (!limb[options.typeKey] || (options.typeKey === 'type' && limb.type.type))
+ ? limb
+ : null)
+ , proto
+ , prefix
+ , keys
+ , options);
+ }
+}
+
+// gets descriptors for all properties of `object`
+// makes all properties non-enumerable to match previous behavior to #2211
+function getOwnPropertyDescriptors(object) {
+ var result = {};
+
+ Object.getOwnPropertyNames(object).forEach(function(key) {
+ result[key] = Object.getOwnPropertyDescriptor(object, key);
+ result[key].enumerable = true;
+ });
+
+ return result;
+}
+
+/*!
+ * Defines the accessor named prop on the incoming prototype.
+ */
+
+function defineKey(prop, subprops, prototype, prefix, keys, options) {
+ var path = (prefix ? prefix + '.' : '') + prop;
+ prefix = prefix || '';
+
+ if (subprops) {
+ Object.defineProperty(prototype, prop, {
+ enumerable: true,
+ configurable: true,
+ get: function() {
+ var _this = this;
+ if (!this.$__.getters) {
+ this.$__.getters = {};
+ }
+
+ if (!this.$__.getters[path]) {
+ var nested = Object.create(Object.getPrototypeOf(this), getOwnPropertyDescriptors(this));
+
+ // save scope for nested getters/setters
+ if (!prefix) {
+ nested.$__.scope = this;
+ }
+
+ // shadow inherited getters from sub-objects so
+ // thing.nested.nested.nested... doesn't occur (gh-366)
+ var i = 0,
+ len = keys.length;
+
+ for (; i < len; ++i) {
+ // over-write the parents getter without triggering it
+ Object.defineProperty(nested, keys[i], {
+ enumerable: false, // It doesn't show up.
+ writable: true, // We can set it later.
+ configurable: true, // We can Object.defineProperty again.
+ value: undefined // It shadows its parent.
+ });
+ }
+
+ Object.defineProperty(nested, 'toObject', {
+ enumerable: true,
+ configurable: true,
+ writable: false,
+ value: function() {
+ return _this.get(path);
+ }
+ });
+
+ Object.defineProperty(nested, 'toJSON', {
+ enumerable: true,
+ configurable: true,
+ writable: false,
+ value: function() {
+ return _this.get(path);
+ }
+ });
+
+ Object.defineProperty(nested, '$__isNested', {
+ enumerable: true,
+ configurable: true,
+ writable: false,
+ value: true
+ });
+
+ compile(subprops, nested, path, options);
+ this.$__.getters[path] = nested;
+ }
+
+ return this.$__.getters[path];
+ },
+ set: function(v) {
+ if (v instanceof Document) {
+ v = v.toObject({ transform: false });
+ }
+ return (this.$__.scope || this).set(path, v);
+ }
+ });
+ } else {
+ Object.defineProperty(prototype, prop, {
+ enumerable: true,
+ configurable: true,
+ get: function() {
+ return this.get.call(this.$__.scope || this, path);
+ },
+ set: function(v) {
+ return this.set.call(this.$__.scope || this, path, v);
+ }
+ });
+ }
+}
+
+/**
+ * Assigns/compiles `schema` into this documents prototype.
+ *
+ * @param {Schema} schema
+ * @api private
+ * @method $__setSchema
+ * @memberOf Document
+ */
+
+Document.prototype.$__setSchema = function(schema) {
+ compile(schema.tree, this, undefined, schema.options);
+ this.schema = schema;
+};
+
+
+/**
+ * Get active path that were changed and are arrays
+ *
+ * @api private
+ * @method $__getArrayPathsToValidate
+ * @memberOf Document
+ */
+
+Document.prototype.$__getArrayPathsToValidate = function() {
+ DocumentArray || (DocumentArray = require('./types/documentarray'));
+
+ // validate all document arrays.
+ return this.$__.activePaths
+ .map('init', 'modify', function(i) {
+ return this.getValue(i);
+ }.bind(this))
+ .filter(function(val) {
+ return val && val instanceof Array && val.isMongooseDocumentArray && val.length;
+ }).reduce(function(seed, array) {
+ return seed.concat(array);
+ }, [])
+ .filter(function(doc) {
+ return doc;
+ });
+};
+
+
+/**
+ * Get all subdocs (by bfs)
+ *
+ * @api private
+ * @method $__getAllSubdocs
+ * @memberOf Document
+ */
+
+Document.prototype.$__getAllSubdocs = function() {
+ DocumentArray || (DocumentArray = require('./types/documentarray'));
+ Embedded = Embedded || require('./types/embedded');
+
+ function docReducer(seed, path) {
+ var val = this[path];
+
+ if (val instanceof Embedded) {
+ seed.push(val);
+ }
+ if (val && val.$isSingleNested) {
+ seed = Object.keys(val._doc).reduce(docReducer.bind(val._doc), seed);
+ seed.push(val);
+ }
+ if (val && val.isMongooseDocumentArray) {
+ val.forEach(function _docReduce(doc) {
+ if (!doc || !doc._doc) {
+ return;
+ }
+ if (doc instanceof Embedded) {
+ seed.push(doc);
+ }
+ seed = Object.keys(doc._doc).reduce(docReducer.bind(doc._doc), seed);
+ });
+ } else if (val instanceof Document && val.$__isNested) {
+ val = val.toObject();
+ if (val) {
+ seed = Object.keys(val).reduce(docReducer.bind(val), seed);
+ }
+ }
+ return seed;
+ }
+
+ var subDocs = Object.keys(this._doc).reduce(docReducer.bind(this), []);
+
+ return subDocs;
+};
+
+/**
+ * Executes methods queued from the Schema definition
+ *
+ * @api private
+ * @method $__registerHooksFromSchema
+ * @memberOf Document
+ */
+
+Document.prototype.$__registerHooksFromSchema = function() {
+ Embedded = Embedded || require('./types/embedded');
+ var Promise = PromiseProvider.get();
+
+ var _this = this;
+ var q = _this.schema && _this.schema.callQueue;
+ if (!q.length) {
+ return _this;
+ }
+
+ // we are only interested in 'pre' hooks, and group by point-cut
+ var toWrap = q.reduce(function(seed, pair) {
+ if (pair[0] !== 'pre' && pair[0] !== 'post' && pair[0] !== 'on') {
+ _this[pair[0]].apply(_this, pair[1]);
+ return seed;
+ }
+ var args = [].slice.call(pair[1]);
+ var pointCut = pair[0] === 'on' ? 'post' : args[0];
+ if (!(pointCut in seed)) {
+ seed[pointCut] = {post: [], pre: []};
+ }
+ if (pair[0] === 'post') {
+ seed[pointCut].post.push(args);
+ } else if (pair[0] === 'on') {
+ seed[pointCut].push(args);
+ } else {
+ seed[pointCut].pre.push(args);
+ }
+ return seed;
+ }, {post: []});
+
+ // 'post' hooks are simpler
+ toWrap.post.forEach(function(args) {
+ _this.on.apply(_this, args);
+ });
+ delete toWrap.post;
+
+ // 'init' should be synchronous on subdocuments
+ if (toWrap.init && _this instanceof Embedded) {
+ if (toWrap.init.pre) {
+ toWrap.init.pre.forEach(function(args) {
+ _this.$pre.apply(_this, args);
+ });
+ }
+ if (toWrap.init.post) {
+ toWrap.init.post.forEach(function(args) {
+ _this.$post.apply(_this, args);
+ });
+ }
+ delete toWrap.init;
+ } else if (toWrap.set) {
+ // Set hooks also need to be sync re: gh-3479
+ if (toWrap.set.pre) {
+ toWrap.set.pre.forEach(function(args) {
+ _this.$pre.apply(_this, args);
+ });
+ }
+ if (toWrap.set.post) {
+ toWrap.set.post.forEach(function(args) {
+ _this.$post.apply(_this, args);
+ });
+ }
+ delete toWrap.set;
+ }
+
+ Object.keys(toWrap).forEach(function(pointCut) {
+ // this is so we can wrap everything into a promise;
+ var newName = ('$__original_' + pointCut);
+ if (!_this[pointCut]) {
+ return;
+ }
+ _this[newName] = _this[pointCut];
+ _this[pointCut] = function wrappedPointCut() {
+ var args = [].slice.call(arguments);
+ var lastArg = args.pop();
+ var fn;
+ var originalError = new Error();
+ var $results;
+ if (lastArg && typeof lastArg !== 'function') {
+ args.push(lastArg);
+ } else {
+ fn = lastArg;
+ }
+
+ var promise = new Promise.ES6(function(resolve, reject) {
+ args.push(function(error) {
+ if (error) {
+ // gh-2633: since VersionError is very generic, take the
+ // stack trace of the original save() function call rather
+ // than the async trace
+ if (error instanceof VersionError) {
+ error.stack = originalError.stack;
+ }
+ _this.$__handleReject(error);
+ reject(error);
+ return;
+ }
+
+ // There may be multiple results and promise libs other than
+ // mpromise don't support passing multiple values to `resolve()`
+ $results = Array.prototype.slice.call(arguments, 1);
+ resolve.apply(promise, $results);
+ });
+
+ _this[newName].apply(_this, args);
+ });
+ if (fn) {
+ if (_this.constructor.$wrapCallback) {
+ fn = _this.constructor.$wrapCallback(fn);
+ }
+ return promise.then(
+ function() {
+ process.nextTick(function() {
+ fn.apply(null, [null].concat($results));
+ });
+ },
+ function(error) {
+ process.nextTick(function() {
+ fn(error);
+ });
+ });
+ }
+ return promise;
+ };
+
+ toWrap[pointCut].pre.forEach(function(args) {
+ args[0] = newName;
+ _this.$pre.apply(_this, args);
+ });
+ toWrap[pointCut].post.forEach(function(args) {
+ args[0] = newName;
+ _this.$post.apply(_this, args);
+ });
+ });
+ return _this;
+};
+
+Document.prototype.$__handleReject = function handleReject(err) {
+ // emit on the Model if listening
+ if (this.listeners('error').length) {
+ this.emit('error', err);
+ } else if (this.constructor.listeners && this.constructor.listeners('error').length) {
+ this.constructor.emit('error', err);
+ } else if (this.listeners && this.listeners('error').length) {
+ this.emit('error', err);
+ }
+};
+
+/**
+ * Internal helper for toObject() and toJSON() that doesn't manipulate options
+ *
+ * @api private
+ * @method $toObject
+ * @memberOf Document
+ */
+
+Document.prototype.$toObject = function(options, json) {
+ var defaultOptions = {
+ transform: true,
+ json: json,
+ retainKeyOrder: this.schema.options.retainKeyOrder
+ };
+
+ // _isNested will only be true if this is not the top level document, we
+ // should never depopulate
+ if (options && options.depopulate && options._isNested && this.$__.wasPopulated) {
+ // populated paths that we set to a document
+ return clone(this._id, options);
+ }
+
+ // When internally saving this document we always pass options,
+ // bypassing the custom schema options.
+ if (!(options && utils.getFunctionName(options.constructor) === 'Object') ||
+ (options && options._useSchemaOptions)) {
+ if (json) {
+ options = this.schema.options.toJSON ?
+ clone(this.schema.options.toJSON) :
+ {};
+ options.json = true;
+ options._useSchemaOptions = true;
+ } else {
+ options = this.schema.options.toObject ?
+ clone(this.schema.options.toObject) :
+ {};
+ options.json = false;
+ options._useSchemaOptions = true;
+ }
+ }
+
+ for (var key in defaultOptions) {
+ if (options[key] === undefined) {
+ options[key] = defaultOptions[key];
+ }
+ }
+
+ ('minimize' in options) || (options.minimize = this.schema.options.minimize);
+
+ // remember the root transform function
+ // to save it from being overwritten by sub-transform functions
+ var originalTransform = options.transform;
+
+ options._isNested = true;
+
+ var ret = clone(this._doc, options) || {};
+
+ if (options.getters) {
+ applyGetters(this, ret, 'paths', options);
+ // applyGetters for paths will add nested empty objects;
+ // if minimize is set, we need to remove them.
+ if (options.minimize) {
+ ret = minimize(ret) || {};
+ }
+ }
+
+ if (options.virtuals || options.getters && options.virtuals !== false) {
+ applyGetters(this, ret, 'virtuals', options);
+ }
+
+ if (options.versionKey === false && this.schema.options.versionKey) {
+ delete ret[this.schema.options.versionKey];
+ }
+
+ var transform = options.transform;
+
+ // In the case where a subdocument has its own transform function, we need to
+ // check and see if the parent has a transform (options.transform) and if the
+ // child schema has a transform (this.schema.options.toObject) In this case,
+ // we need to adjust options.transform to be the child schema's transform and
+ // not the parent schema's
+ if (transform === true ||
+ (this.schema.options.toObject && transform)) {
+ var opts = options.json ? this.schema.options.toJSON : this.schema.options.toObject;
+
+ if (opts) {
+ transform = (typeof options.transform === 'function' ? options.transform : opts.transform);
+ }
+ } else {
+ options.transform = originalTransform;
+ }
+
+ if (typeof transform === 'function') {
+ var xformed = transform(this, ret, options);
+ if (typeof xformed !== 'undefined') {
+ ret = xformed;
+ }
+ }
+
+ return ret;
+};
+
+/**
+ * Converts this document into a plain javascript object, ready for storage in MongoDB.
+ *
+ * Buffers are converted to instances of [mongodb.Binary](http://mongodb.github.com/node-mongodb-native/api-bson-generated/binary.html) for proper storage.
+ *
+ * ####Options:
+ *
+ * - `getters` apply all getters (path and virtual getters)
+ * - `virtuals` apply virtual getters (can override `getters` option)
+ * - `minimize` remove empty objects (defaults to true)
+ * - `transform` a transform function to apply to the resulting document before returning
+ * - `depopulate` depopulate any populated paths, replacing them with their original refs (defaults to false)
+ * - `versionKey` whether to include the version key (defaults to true)
+ * - `retainKeyOrder` keep the order of object keys. If this is set to true, `Object.keys(new Doc({ a: 1, b: 2}).toObject())` will always produce `['a', 'b']` (defaults to false)
+ *
+ * ####Getters/Virtuals
+ *
+ * Example of only applying path getters
+ *
+ * doc.toObject({ getters: true, virtuals: false })
+ *
+ * Example of only applying virtual getters
+ *
+ * doc.toObject({ virtuals: true })
+ *
+ * Example of applying both path and virtual getters
+ *
+ * doc.toObject({ getters: true })
+ *
+ * To apply these options to every document of your schema by default, set your [schemas](#schema_Schema) `toObject` option to the same argument.
+ *
+ * schema.set('toObject', { virtuals: true })
+ *
+ * ####Transform
+ *
+ * We may need to perform a transformation of the resulting object based on some criteria, say to remove some sensitive information or return a custom object. In this case we set the optional `transform` function.
+ *
+ * Transform functions receive three arguments
+ *
+ * function (doc, ret, options) {}
+ *
+ * - `doc` The mongoose document which is being converted
+ * - `ret` The plain object representation which has been converted
+ * - `options` The options in use (either schema options or the options passed inline)
+ *
+ * ####Example
+ *
+ * // specify the transform schema option
+ * if (!schema.options.toObject) schema.options.toObject = {};
+ * schema.options.toObject.transform = function (doc, ret, options) {
+ * // remove the _id of every document before returning the result
+ * delete ret._id;
+ * return ret;
+ * }
+ *
+ * // without the transformation in the schema
+ * doc.toObject(); // { _id: 'anId', name: 'Wreck-it Ralph' }
+ *
+ * // with the transformation
+ * doc.toObject(); // { name: 'Wreck-it Ralph' }
+ *
+ * With transformations we can do a lot more than remove properties. We can even return completely new customized objects:
+ *
+ * if (!schema.options.toObject) schema.options.toObject = {};
+ * schema.options.toObject.transform = function (doc, ret, options) {
+ * return { movie: ret.name }
+ * }
+ *
+ * // without the transformation in the schema
+ * doc.toObject(); // { _id: 'anId', name: 'Wreck-it Ralph' }
+ *
+ * // with the transformation
+ * doc.toObject(); // { movie: 'Wreck-it Ralph' }
+ *
+ * _Note: if a transform function returns `undefined`, the return value will be ignored._
+ *
+ * Transformations may also be applied inline, overridding any transform set in the options:
+ *
+ * function xform (doc, ret, options) {
+ * return { inline: ret.name, custom: true }
+ * }
+ *
+ * // pass the transform as an inline option
+ * doc.toObject({ transform: xform }); // { inline: 'Wreck-it Ralph', custom: true }
+ *
+ * _Note: if you call `toObject` and pass any options, the transform declared in your schema options will __not__ be applied. To force its application pass `transform: true`_
+ *
+ * if (!schema.options.toObject) schema.options.toObject = {};
+ * schema.options.toObject.hide = '_id';
+ * schema.options.toObject.transform = function (doc, ret, options) {
+ * if (options.hide) {
+ * options.hide.split(' ').forEach(function (prop) {
+ * delete ret[prop];
+ * });
+ * }
+ * return ret;
+ * }
+ *
+ * var doc = new Doc({ _id: 'anId', secret: 47, name: 'Wreck-it Ralph' });
+ * doc.toObject(); // { secret: 47, name: 'Wreck-it Ralph' }
+ * doc.toObject({ hide: 'secret _id' }); // { _id: 'anId', secret: 47, name: 'Wreck-it Ralph' }
+ * doc.toObject({ hide: 'secret _id', transform: true }); // { name: 'Wreck-it Ralph' }
+ *
+ * Transforms are applied _only to the document and are not applied to sub-documents_.
+ *
+ * Transforms, like all of these options, are also available for `toJSON`.
+ *
+ * See [schema options](/docs/guide.html#toObject) for some more details.
+ *
+ * _During save, no custom options are applied to the document before being sent to the database._
+ *
+ * @param {Object} [options]
+ * @return {Object} js object
+ * @see mongodb.Binary http://mongodb.github.com/node-mongodb-native/api-bson-generated/binary.html
+ * @api public
+ */
+
+Document.prototype.toObject = function(options) {
+ return this.$toObject(options);
+};
+
+/*!
+ * Minimizes an object, removing undefined values and empty objects
+ *
+ * @param {Object} object to minimize
+ * @return {Object}
+ */
+
+function minimize(obj) {
+ var keys = Object.keys(obj),
+ i = keys.length,
+ hasKeys,
+ key,
+ val;
+
+ while (i--) {
+ key = keys[i];
+ val = obj[key];
+
+ if (utils.isObject(val)) {
+ obj[key] = minimize(val);
+ }
+
+ if (undefined === obj[key]) {
+ delete obj[key];
+ continue;
+ }
+
+ hasKeys = true;
+ }
+
+ return hasKeys
+ ? obj
+ : undefined;
+}
+
+/*!
+ * Applies virtuals properties to `json`.
+ *
+ * @param {Document} self
+ * @param {Object} json
+ * @param {String} type either `virtuals` or `paths`
+ * @return {Object} `json`
+ */
+
+function applyGetters(self, json, type, options) {
+ var schema = self.schema,
+ paths = Object.keys(schema[type]),
+ i = paths.length,
+ path;
+
+ while (i--) {
+ path = paths[i];
+
+ var parts = path.split('.'),
+ plen = parts.length,
+ last = plen - 1,
+ branch = json,
+ part;
+
+ for (var ii = 0; ii < plen; ++ii) {
+ part = parts[ii];
+ if (ii === last) {
+ branch[part] = clone(self.get(path), options);
+ } else {
+ branch = branch[part] || (branch[part] = {});
+ }
+ }
+ }
+
+ return json;
+}
+
+/**
+ * The return value of this method is used in calls to JSON.stringify(doc).
+ *
+ * This method accepts the same options as [Document#toObject](#document_Document-toObject). To apply the options to every document of your schema by default, set your [schemas](#schema_Schema) `toJSON` option to the same argument.
+ *
+ * schema.set('toJSON', { virtuals: true })
+ *
+ * See [schema options](/docs/guide.html#toJSON) for details.
+ *
+ * @param {Object} options
+ * @return {Object}
+ * @see Document#toObject #document_Document-toObject
+ * @api public
+ */
+
+Document.prototype.toJSON = function(options) {
+ return this.$toObject(options, true);
+};
+
+/**
+ * Helper for console.log
+ *
+ * @api public
+ */
+
+Document.prototype.inspect = function(options) {
+ var isPOJO = options &&
+ utils.getFunctionName(options.constructor) === 'Object';
+ var opts;
+ if (isPOJO) {
+ opts = options;
+ opts.minimize = false;
+ opts.retainKeyOrder = true;
+ }
+ return this.toObject(opts);
+};
+
+/**
+ * Helper for console.log
+ *
+ * @api public
+ * @method toString
+ */
+
+Document.prototype.toString = function() {
+ return inspect(this.inspect());
+};
+
+/**
+ * Returns true if the Document stores the same data as doc.
+ *
+ * Documents are considered equal when they have matching `_id`s, unless neither
+ * document has an `_id`, in which case this function falls back to using
+ * `deepEqual()`.
+ *
+ * @param {Document} doc a document to compare
+ * @return {Boolean}
+ * @api public
+ */
+
+Document.prototype.equals = function(doc) {
+ if (!doc) {
+ return false;
+ }
+
+ var tid = this.get('_id');
+ var docid = doc.get ? doc.get('_id') : doc;
+ if (!tid && !docid) {
+ return deepEqual(this, doc);
+ }
+ return tid && tid.equals
+ ? tid.equals(docid)
+ : tid === docid;
+};
+
+/**
+ * Populates document references, executing the `callback` when complete.
+ * If you want to use promises instead, use this function with
+ * [`execPopulate()`](#document_Document-execPopulate)
+ *
+ * ####Example:
+ *
+ * doc
+ * .populate('company')
+ * .populate({
+ * path: 'notes',
+ * match: /airline/,
+ * select: 'text',
+ * model: 'modelName'
+ * options: opts
+ * }, function (err, user) {
+ * assert(doc._id === user._id) // the document itself is passed
+ * })
+ *
+ * // summary
+ * doc.populate(path) // not executed
+ * doc.populate(options); // not executed
+ * doc.populate(path, callback) // executed
+ * doc.populate(options, callback); // executed
+ * doc.populate(callback); // executed
+ * doc.populate(options).execPopulate() // executed, returns promise
+ *
+ *
+ * ####NOTE:
+ *
+ * Population does not occur unless a `callback` is passed *or* you explicitly
+ * call `execPopulate()`.
+ * Passing the same path a second time will overwrite the previous path options.
+ * See [Model.populate()](#model_Model.populate) for explaination of options.
+ *
+ * @see Model.populate #model_Model.populate
+ * @see Document.execPopulate #document_Document-execPopulate
+ * @param {String|Object} [path] The path to populate or an options object
+ * @param {Function} [callback] When passed, population is invoked
+ * @api public
+ * @return {Document} this
+ */
+
+Document.prototype.populate = function populate() {
+ if (arguments.length === 0) {
+ return this;
+ }
+
+ var pop = this.$__.populate || (this.$__.populate = {});
+ var args = utils.args(arguments);
+ var fn;
+
+ if (typeof args[args.length - 1] === 'function') {
+ fn = args.pop();
+ }
+
+ // allow `doc.populate(callback)`
+ if (args.length) {
+ // use hash to remove duplicate paths
+ var res = utils.populate.apply(null, args);
+ for (var i = 0; i < res.length; ++i) {
+ pop[res[i].path] = res[i];
+ }
+ }
+
+ if (fn) {
+ var paths = utils.object.vals(pop);
+ this.$__.populate = undefined;
+ paths.__noPromise = true;
+ this.constructor.populate(this, paths, fn);
+ }
+
+ return this;
+};
+
+/**
+ * Explicitly executes population and returns a promise. Useful for ES2015
+ * integration.
+ *
+ * ####Example:
+ *
+ * var promise = doc.
+ * populate('company').
+ * populate({
+ * path: 'notes',
+ * match: /airline/,
+ * select: 'text',
+ * model: 'modelName'
+ * options: opts
+ * }).
+ * execPopulate();
+ *
+ * // summary
+ * doc.execPopulate().then(resolve, reject);
+ *
+ *
+ * @see Document.populate #document_Document-populate
+ * @api public
+ * @return {Promise} promise that resolves to the document when population is done
+ */
+
+Document.prototype.execPopulate = function() {
+ var Promise = PromiseProvider.get();
+ var _this = this;
+ return new Promise.ES6(function(resolve, reject) {
+ _this.populate(function(error, res) {
+ if (error) {
+ reject(error);
+ } else {
+ resolve(res);
+ }
+ });
+ });
+};
+
+/**
+ * Gets _id(s) used during population of the given `path`.
+ *
+ * ####Example:
+ *
+ * Model.findOne().populate('author').exec(function (err, doc) {
+ * console.log(doc.author.name) // Dr.Seuss
+ * console.log(doc.populated('author')) // '5144cf8050f071d979c118a7'
+ * })
+ *
+ * If the path was not populated, undefined is returned.
+ *
+ * @param {String} path
+ * @return {Array|ObjectId|Number|Buffer|String|undefined}
+ * @api public
+ */
+
+Document.prototype.populated = function(path, val, options) {
+ // val and options are internal
+
+ if (val === null || val === void 0) {
+ if (!this.$__.populated) {
+ return undefined;
+ }
+ var v = this.$__.populated[path];
+ if (v) {
+ return v.value;
+ }
+ return undefined;
+ }
+
+ // internal
+
+ if (val === true) {
+ if (!this.$__.populated) {
+ return undefined;
+ }
+ return this.$__.populated[path];
+ }
+
+ this.$__.populated || (this.$__.populated = {});
+ this.$__.populated[path] = {value: val, options: options};
+ return val;
+};
+
+/**
+ * Takes a populated field and returns it to its unpopulated state.
+ *
+ * ####Example:
+ *
+ * Model.findOne().populate('author').exec(function (err, doc) {
+ * console.log(doc.author.name); // Dr.Seuss
+ * console.log(doc.depopulate('author'));
+ * console.log(doc.author); // '5144cf8050f071d979c118a7'
+ * })
+ *
+ * If the path was not populated, this is a no-op.
+ *
+ * @param {String} path
+ * @see Document.populate #document_Document-populate
+ * @api public
+ */
+
+Document.prototype.depopulate = function(path) {
+ var populatedIds = this.populated(path);
+ if (!populatedIds) {
+ return;
+ }
+ delete this.$__.populated[path];
+ this.set(path, populatedIds);
+};
+
+
+/**
+ * Returns the full path to this document.
+ *
+ * @param {String} [path]
+ * @return {String}
+ * @api private
+ * @method $__fullPath
+ * @memberOf Document
+ */
+
+Document.prototype.$__fullPath = function(path) {
+ // overridden in SubDocuments
+ return path || '';
+};
+
+/*!
+ * Module exports.
+ */
+
+Document.ValidationError = ValidationError;
+module.exports = exports = Document;
diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/document_provider.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/document_provider.js
new file mode 100644
index 0000000..10087cc
--- /dev/null
+++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/document_provider.js
@@ -0,0 +1,21 @@
+'use strict';
+
+/* eslint-env browser */
+
+/*!
+ * 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;
+ }
+ return Document;
+};
diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/document_provider.web.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/document_provider.web.js
new file mode 100644
index 0000000..4223fc3
--- /dev/null
+++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/document_provider.web.js
@@ -0,0 +1,17 @@
+'use strict';
+
+/* eslint-env browser */
+
+/*!
+ * Module dependencies.
+ */
+var BrowserDocument = require('./browserDocument.js');
+
+/**
+ * Returns the Document constructor for the current context
+ *
+ * @api private
+ */
+module.exports = function() {
+ return BrowserDocument;
+};
diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/drivers/SPEC.md b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/drivers/SPEC.md
new file mode 100644
index 0000000..6464693
--- /dev/null
+++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/drivers/SPEC.md
@@ -0,0 +1,4 @@
+
+# Driver Spec
+
+TODO
diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/drivers/browser/ReadPreference.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/drivers/browser/ReadPreference.js
new file mode 100644
index 0000000..f20cd6c
--- /dev/null
+++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/drivers/browser/ReadPreference.js
@@ -0,0 +1,5 @@
+/*!
+ * ignore
+ */
+
+module.exports = function() {};
diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/drivers/browser/binary.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/drivers/browser/binary.js
new file mode 100644
index 0000000..4d7a395
--- /dev/null
+++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/drivers/browser/binary.js
@@ -0,0 +1,12 @@
+
+/*!
+ * Module dependencies.
+ */
+
+var Binary = require('bson').Binary;
+
+/*!
+ * Module exports.
+ */
+
+module.exports = exports = Binary;
diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/drivers/browser/index.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/drivers/browser/index.js
new file mode 100644
index 0000000..fa5dbb4
--- /dev/null
+++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/drivers/browser/index.js
@@ -0,0 +1,7 @@
+/*!
+ * Module exports.
+ */
+
+exports.Binary = require('./binary');
+exports.ObjectId = require('./objectid');
+exports.ReadPreference = require('./ReadPreference');
diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/drivers/browser/objectid.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/drivers/browser/objectid.js
new file mode 100644
index 0000000..e63c04a
--- /dev/null
+++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/drivers/browser/objectid.js
@@ -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;
diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/drivers/index.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/drivers/index.js
new file mode 100644
index 0000000..5a842ba
--- /dev/null
+++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/drivers/index.js
@@ -0,0 +1,17 @@
+/*!
+ * ignore
+ */
+
+var driver;
+
+if (typeof window === 'undefined') {
+ driver = require(global.MONGOOSE_DRIVER_PATH || './node-mongodb-native');
+} else {
+ driver = require('./browser');
+}
+
+/*!
+ * ignore
+ */
+
+module.exports = driver;
diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/drivers/index.web.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/drivers/index.web.js
new file mode 100644
index 0000000..f833eb2
--- /dev/null
+++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/drivers/index.web.js
@@ -0,0 +1,5 @@
+/*!
+ * ignore
+ */
+
+module.exports = require('./browser');
diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/drivers/node-mongodb-native/ReadPreference.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/drivers/node-mongodb-native/ReadPreference.js
new file mode 100644
index 0000000..e921d60
--- /dev/null
+++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/drivers/node-mongodb-native/ReadPreference.js
@@ -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);
+};
diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/drivers/node-mongodb-native/binary.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/drivers/node-mongodb-native/binary.js
new file mode 100644
index 0000000..657efde
--- /dev/null
+++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/drivers/node-mongodb-native/binary.js
@@ -0,0 +1,8 @@
+
+/*!
+ * Module dependencies.
+ */
+
+var Binary = require('mongodb').Binary;
+
+module.exports = exports = Binary;
diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/drivers/node-mongodb-native/collection.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/drivers/node-mongodb-native/collection.js
new file mode 100644
index 0000000..fd0da30
--- /dev/null
+++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/drivers/node-mongodb-native/collection.js
@@ -0,0 +1,267 @@
+/*!
+ * Module dependencies.
+ */
+
+var MongooseCollection = require('../../collection'),
+ Collection = require('mongodb').Collection,
+ 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 _this = this;
+
+ // always get a new collection in case the user changed host:port
+ // of parent db instance when re-opening the connection.
+
+ if (!_this.opts.capped.size) {
+ // non-capped
+ callback(null, _this.conn.db.collection(_this.name));
+ return _this.collection;
+ }
+
+ // capped
+ return _this.conn.db.collection(_this.name, function(err, c) {
+ if (err) return callback(err);
+
+ // discover if this collection exists and if it is capped
+ _this.conn.db.listCollections({name: _this.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: ' + _this.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(_this.opts.capped);
+ opts.capped = true;
+ _this.conn.db.createCollection(_this.name, opts, callback);
+ }
+ });
+ });
+
+ function callback(err, collection) {
+ if (err) {
+ // likely a strict mode error
+ _this.conn.emit('error', err);
+ } else {
+ _this.collection = collection;
+ MongooseCollection.prototype.onOpen.call(_this);
+ }
+ }
+};
+
+/**
+ * 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
+ */
+
+function iter(i) {
+ NativeCollection.prototype[i] = function() {
+ if (this.buffer) {
+ this.addQueue(i, arguments);
+ return;
+ }
+
+ var collection = this.collection,
+ args = arguments,
+ _this = this,
+ debug = _this.conn.base.options.debug;
+
+ if (debug) {
+ if (typeof debug === 'function') {
+ debug.apply(debug,
+ [_this.name, i].concat(utils.args(args, 0, args.length - 1)));
+ } else {
+ this.$print(_this.name, i, args);
+ }
+ }
+
+ try {
+ return collection[i].apply(collection, args);
+ } catch (error) {
+ // Collection operation may throw because of max bson size, catch it here
+ // See gh-3906
+ if (args.length > 0 &&
+ typeof args[args.length - 1] === 'function') {
+ args[args.length - 1](error);
+ } else {
+ throw error;
+ }
+ }
+ };
+}
+
+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;
+ }
+
+ iter(i);
+}
+
+/**
+ * Debug print helper
+ *
+ * @api public
+ * @method $print
+ */
+
+NativeCollection.prototype.$print = function(name, i, args) {
+ var moduleName = '\x1B[0;36mMongoose:\x1B[0m ';
+ var functionCall = [name, i].join('.');
+ var _args = [];
+ for (var j = args.length - 1; j >= 0; --j) {
+ if (this.$format(args[j]) || _args.length) {
+ _args.unshift(this.$format(args[j]));
+ }
+ }
+ var params = '(' + _args.join(', ') + ')';
+
+ console.error(moduleName + functionCall + params);
+};
+
+/**
+ * Formatter for debug print args
+ *
+ * @api public
+ * @method $format
+ */
+
+NativeCollection.prototype.$format = function(arg) {
+ var type = typeof arg;
+ if (type === 'function' || type === 'undefined') return '';
+ return format(arg);
+};
+
+/*!
+ * Debug print helper
+ */
+
+function map(o) {
+ return format(o, true);
+}
+function formatObjectId(x, key) {
+ var representation = 'ObjectId("' + x[key].toHexString() + '")';
+ x[key] = {inspect: function() { return representation; }};
+}
+function formatDate(x, key) {
+ var representation = 'new Date("' + x[key].toUTCString() + '")';
+ x[key] = {inspect: function() { return representation; }};
+}
+function format(obj, sub) {
+ if (obj && typeof obj.toBSON === 'function') {
+ obj = obj.toBSON();
+ }
+ var x = utils.clone(obj, {retainKeyOrder: 1, transform: false});
+ var representation;
+
+ if (x != null) {
+ if (x.constructor.name === 'Binary') {
+ x = 'BinData(' + x.sub_type + ', "' + x.toString('base64') + '")';
+ } else if (x.constructor.name === 'ObjectID') {
+ representation = 'ObjectId("' + x.toHexString() + '")';
+ x = {inspect: function() { return representation; }};
+ } else if (x.constructor.name === 'Date') {
+ representation = 'new Date("' + x.toUTCString() + '")';
+ x = {inspect: function() { return representation; }};
+ } else if (x.constructor.name === 'Object') {
+ 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 (typeof x[key].toBSON === 'function') {
+ x[key] = x[key].toBSON();
+ }
+ if (x[key].constructor.name === 'Binary') {
+ x[key] = 'BinData(' + x[key].sub_type + ', "' +
+ x[key].buffer.toString('base64') + '")';
+ } else if (x[key].constructor.name === 'Object') {
+ x[key] = format(x[key], true);
+ } else if (x[key].constructor.name === 'ObjectID') {
+ formatObjectId(x, key);
+ } else if (x[key].constructor.name === 'Date') {
+ formatDate(x, key);
+ } else if (Array.isArray(x[key])) {
+ x[key] = x[key].map(map);
+ }
+ }
+ }
+ }
+ 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;
diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/drivers/node-mongodb-native/connection.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/drivers/node-mongodb-native/connection.js
new file mode 100644
index 0000000..c17330d
--- /dev/null
+++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/drivers/node-mongodb-native/connection.js
@@ -0,0 +1,386 @@
+/*!
+ * Module dependencies.
+ */
+
+var MongooseConnection = require('../../connection');
+var mongo = require('mongodb');
+var Db = mongo.Db;
+var Server = mongo.Server;
+var Mongos = mongo.Mongos;
+var STATES = require('../../connectionstate');
+var ReplSetServers = mongo.ReplSet;
+var DisconnectedError = require('../../error/disconnected');
+
+/**
+ * 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) {
+ var _this = this;
+ var server = new Server(this.host, this.port, this.options.server);
+
+ if (this.options && this.options.mongos) {
+ var mongos = new Mongos([server], this.options.mongos);
+ this.db = new Db(this.name, mongos, this.options.db);
+ } else {
+ this.db = new Db(this.name, server, this.options.db);
+ }
+
+ this.db.open(function(err) {
+ listen(_this);
+
+ if (!mongos) {
+ server.s.server.on('error', function(error) {
+ if (/after \d+ attempts/.test(error.message)) {
+ _this.emit('error', new DisconnectedError(server.s.server.name));
+ }
+ });
+ }
+
+ if (err) return fn(err);
+
+ 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 _this = this;
+
+ if (this.db && this._readyState === STATES.connected) {
+ wireup();
+ } else {
+ this.once('connected', wireup);
+ }
+
+ function wireup() {
+ newConn.db = _this.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.db._listening) {
+ return;
+ }
+ conn.db._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);
+ });
+}
+
+/**
+ * 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) {
+ var servers = [],
+ _this = this;
+
+ this.hosts.forEach(function(server) {
+ var host = server.host || server.ipc;
+ var port = server.port || 27017;
+ servers.push(new Server(host, port, _this.options.server));
+ });
+
+ var server = this.options.mongos
+ ? new Mongos(servers, this.options.mongos)
+ : new ReplSetServers(servers, this.options.replset || this.options.replSet);
+ this.db = new Db(this.name, server, this.options.db);
+
+ this.db.on('fullsetup', function() {
+ _this.emit('fullsetup');
+ });
+
+ this.db.on('all', function() {
+ _this.emit('all');
+ });
+
+ this.db.open(function(err) {
+ if (err) return fn(err);
+ fn();
+ listen(_this);
+ });
+
+ return this;
+};
+
+/**
+ * Closes the connection
+ *
+ * @param {Function} fn
+ * @return {Connection} this
+ * @api private
+ */
+
+NativeConnection.prototype.doClose = function(fn) {
+ this.db.close(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.replSet) || (o.replset = {});
+ o.server.socketOptions || (o.server.socketOptions = {});
+ o.replset.socketOptions || (o.replset.socketOptions = {});
+ o.mongos || (o.mongos = (connStrOpts && connStrOpts.mongos));
+ (o.mongos === true) && (o.mongos = {});
+
+ var opts = connStrOpts || {};
+ Object.keys(opts).forEach(function(name) {
+ switch (name) {
+ case 'ssl':
+ o.server.ssl = opts.ssl;
+ o.replset.ssl = opts.ssl;
+ o.mongos && (o.mongos.ssl = opts.ssl);
+ break;
+ case 'poolSize':
+ if (typeof o.server[name] === 'undefined') {
+ o.server[name] = o.replset[name] = opts[name];
+ }
+ break;
+ case 'slaveOk':
+ if (typeof o.server.slave_ok === 'undefined') {
+ o.server.slave_ok = opts[name];
+ }
+ break;
+ case 'autoReconnect':
+ if (typeof o.server.auto_reconnect === 'undefined') {
+ o.server.auto_reconnect = opts[name];
+ }
+ break;
+ case 'socketTimeoutMS':
+ case 'connectTimeoutMS':
+ if (typeof o.server.socketOptions[name] === 'undefined') {
+ o.server.socketOptions[name] = o.replset.socketOptions[name] = opts[name];
+ }
+ break;
+ case 'authdb':
+ if (typeof o.auth.authdb === 'undefined') {
+ o.auth.authdb = opts[name];
+ }
+ break;
+ case 'authSource':
+ if (typeof o.auth.authSource === 'undefined') {
+ o.auth.authSource = opts[name];
+ }
+ break;
+ case 'retries':
+ case 'reconnectWait':
+ case 'rs_name':
+ if (typeof o.replset[name] === 'undefined') {
+ o.replset[name] = opts[name];
+ }
+ break;
+ case 'replicaSet':
+ if (typeof o.replset.rs_name === 'undefined') {
+ o.replset.rs_name = opts[name];
+ }
+ break;
+ case 'readSecondary':
+ if (typeof o.replset.read_secondary === 'undefined') {
+ o.replset.read_secondary = opts[name];
+ }
+ break;
+ case 'nativeParser':
+ if (typeof o.db.native_parser === 'undefined') {
+ o.db.native_parser = opts[name];
+ }
+ break;
+ case 'w':
+ case 'safe':
+ case 'fsync':
+ case 'journal':
+ case 'wtimeoutMS':
+ if (typeof o.db[name] === 'undefined') {
+ o.db[name] = opts[name];
+ }
+ break;
+ case 'readPreference':
+ if (typeof o.db.readPreference === 'undefined') {
+ o.db.readPreference = opts[name];
+ }
+ break;
+ case 'readPreferenceTags':
+ if (typeof o.db.read_preference_tags === 'undefined') {
+ o.db.read_preference_tags = opts[name];
+ }
+ break;
+ case 'sslValidate':
+ o.server.sslValidate = opts.sslValidate;
+ o.replset.sslValidate = opts.sslValidate;
+ o.mongos && (o.mongos.sslValidate = opts.sslValidate);
+ }
+ });
+
+ if (!('auto_reconnect' in o.server)) {
+ o.server.auto_reconnect = true;
+ }
+
+ // 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;
+ }
+
+ if (o.promiseLibrary) {
+ o.db.promiseLibrary = o.promiseLibrary;
+ }
+
+ validate(o);
+ return o;
+};
+
+/*!
+ * Validates the driver db options.
+ *
+ * @param {Object} o
+ */
+
+function validate(o) {
+ if (o.db.w === -1 || o.db.w === 0) {
+ 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;
diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/drivers/node-mongodb-native/index.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/drivers/node-mongodb-native/index.js
new file mode 100644
index 0000000..fa5dbb4
--- /dev/null
+++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/drivers/node-mongodb-native/index.js
@@ -0,0 +1,7 @@
+/*!
+ * Module exports.
+ */
+
+exports.Binary = require('./binary');
+exports.ObjectId = require('./objectid');
+exports.ReadPreference = require('./ReadPreference');
diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/drivers/node-mongodb-native/objectid.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/drivers/node-mongodb-native/objectid.js
new file mode 100644
index 0000000..69fc08f
--- /dev/null
+++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/drivers/node-mongodb-native/objectid.js
@@ -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;
diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/error.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/error.js
new file mode 100644
index 0000000..b084e76
--- /dev/null
+++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/error.js
@@ -0,0 +1,55 @@
+
+/**
+ * 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);
+ if (Error.captureStackTrace) {
+ Error.captureStackTrace(this);
+ } else {
+ 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');
diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/error/browserMissingSchema.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/error/browserMissingSchema.js
new file mode 100644
index 0000000..1c7892e
--- /dev/null
+++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/error/browserMissingSchema.js
@@ -0,0 +1,32 @@
+/*!
+ * Module dependencies.
+ */
+
+var MongooseError = require('../error.js');
+
+/*!
+ * MissingSchema Error constructor.
+ *
+ * @inherits MongooseError
+ */
+
+function MissingSchemaError() {
+ 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;
diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/error/cast.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/error/cast.js
new file mode 100644
index 0000000..f200a9d
--- /dev/null
+++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/error/cast.js
@@ -0,0 +1,60 @@
+/*!
+ * Module dependencies.
+ */
+
+var MongooseError = require('../error.js');
+var util = require('util');
+
+/**
+ * Casting Error constructor.
+ *
+ * @param {String} type
+ * @param {String} value
+ * @inherits MongooseError
+ * @api private
+ */
+
+function CastError(type, value, path, reason) {
+ var stringValue = util.inspect(value);
+ stringValue = stringValue.replace(/^'/, '"').replace(/'$/, '"');
+ if (stringValue.charAt(0) !== '"') {
+ stringValue = '"' + stringValue + '"';
+ }
+ MongooseError.call(this, 'Cast to ' + type + ' failed for value ' +
+ stringValue + ' at path "' + path + '"');
+ if (Error.captureStackTrace) {
+ Error.captureStackTrace(this);
+ } else {
+ this.stack = new Error().stack;
+ }
+ this.stringValue = stringValue;
+ this.name = 'CastError';
+ this.kind = type;
+ this.value = value;
+ this.path = path;
+ this.reason = reason;
+}
+
+/*!
+ * Inherits from MongooseError.
+ */
+
+CastError.prototype = Object.create(MongooseError.prototype);
+CastError.prototype.constructor = MongooseError;
+
+/*!
+ * ignore
+ */
+
+CastError.prototype.setModel = function(model) {
+ this.model = model;
+ this.message = 'Cast to ' + this.kind + ' failed for value ' +
+ this.stringValue + ' at path "' + this.path + '"' + ' for model "' +
+ model.modelName + '"';
+};
+
+/*!
+ * exports
+ */
+
+module.exports = CastError;
diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/error/disconnected.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/error/disconnected.js
new file mode 100644
index 0000000..b4eece1
--- /dev/null
+++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/error/disconnected.js
@@ -0,0 +1,40 @@
+/*!
+ * Module dependencies.
+ */
+
+var MongooseError = require('../error.js');
+
+/**
+ * Casting Error constructor.
+ *
+ * @param {String} type
+ * @param {String} value
+ * @inherits MongooseError
+ * @api private
+ */
+
+function DisconnectedError(connectionString) {
+ MongooseError.call(this, 'Ran out of retries trying to reconnect to "' +
+ connectionString + '". Try setting `server.reconnectTries` and ' +
+ '`server.reconnectInterval` to something higher.');
+ if (Error.captureStackTrace) {
+ Error.captureStackTrace(this);
+ } else {
+ this.stack = new Error().stack;
+ }
+ this.name = 'DisconnectedError';
+}
+
+/*!
+ * Inherits from MongooseError.
+ */
+
+DisconnectedError.prototype = Object.create(MongooseError.prototype);
+DisconnectedError.prototype.constructor = MongooseError;
+
+
+/*!
+ * exports
+ */
+
+module.exports = DisconnectedError;
diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/error/divergentArray.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/error/divergentArray.js
new file mode 100644
index 0000000..1cbaa25
--- /dev/null
+++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/error/divergentArray.js
@@ -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;
diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/error/messages.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/error/messages.js
new file mode 100644
index 0000000..88ddf6e
--- /dev/null
+++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/error/messages.js
@@ -0,0 +1,42 @@
+
+/**
+ * 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.
+ *
+ * @static 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}).';
diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/error/missingSchema.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/error/missingSchema.js
new file mode 100644
index 0000000..25eabfa
--- /dev/null
+++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/error/missingSchema.js
@@ -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;
diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/error/objectExpected.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/error/objectExpected.js
new file mode 100644
index 0000000..fa863bc
--- /dev/null
+++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/error/objectExpected.js
@@ -0,0 +1,35 @@
+/*!
+ * Module dependencies.
+ */
+
+var MongooseError = require('../error.js');
+
+/**
+ * Strict mode error constructor
+ *
+ * @param {String} type
+ * @param {String} value
+ * @inherits MongooseError
+ * @api private
+ */
+
+function ObjectExpectedError(path, val) {
+ MongooseError.call(this, 'Tried to set nested object field `' + path +
+ '` to primitive value `' + val + '` and strict mode is set to throw.');
+ if (Error.captureStackTrace) {
+ Error.captureStackTrace(this);
+ } else {
+ this.stack = new Error().stack;
+ }
+ this.name = 'ObjectExpectedError';
+ this.path = path;
+}
+
+/*!
+ * Inherits from MongooseError.
+ */
+
+ObjectExpectedError.prototype = Object.create(MongooseError.prototype);
+ObjectExpectedError.prototype.constructor = MongooseError;
+
+module.exports = ObjectExpectedError;
diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/error/overwriteModel.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/error/overwriteModel.js
new file mode 100644
index 0000000..c14ae7f
--- /dev/null
+++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/error/overwriteModel.js
@@ -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;
diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/error/strict.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/error/strict.js
new file mode 100644
index 0000000..6e34431
--- /dev/null
+++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/error/strict.js
@@ -0,0 +1,35 @@
+/*!
+ * Module dependencies.
+ */
+
+var MongooseError = require('../error.js');
+
+/**
+ * Strict mode error constructor
+ *
+ * @param {String} type
+ * @param {String} value
+ * @inherits MongooseError
+ * @api private
+ */
+
+function StrictModeError(path) {
+ MongooseError.call(this, 'Field `' + path + '` is not in schema and strict ' +
+ 'mode is set to throw.');
+ if (Error.captureStackTrace) {
+ Error.captureStackTrace(this);
+ } else {
+ this.stack = new Error().stack;
+ }
+ this.name = 'StrictModeError';
+ this.path = path;
+}
+
+/*!
+ * Inherits from MongooseError.
+ */
+
+StrictModeError.prototype = Object.create(MongooseError.prototype);
+StrictModeError.prototype.constructor = MongooseError;
+
+module.exports = StrictModeError;
diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/error/validation.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/error/validation.js
new file mode 100644
index 0000000..e3322d4
--- /dev/null
+++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/error/validation.js
@@ -0,0 +1,63 @@
+/*!
+ * Module requirements
+ */
+
+var MongooseError = require('../error.js');
+
+/**
+ * Document Validation Error
+ *
+ * @api private
+ * @param {Document} instance
+ * @inherits MongooseError
+ */
+
+function ValidationError(instance) {
+ this.errors = {};
+ if (instance && instance.constructor.name === 'model') {
+ MongooseError.call(this, instance.constructor.modelName + ' validation failed');
+ } else {
+ MongooseError.call(this, 'Validation failed');
+ }
+ if (Error.captureStackTrace) {
+ Error.captureStackTrace(this);
+ } else {
+ this.stack = new Error().stack;
+ }
+ this.name = 'ValidationError';
+ 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;
diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/error/validator.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/error/validator.js
new file mode 100644
index 0000000..96a3ba1
--- /dev/null
+++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/error/validator.js
@@ -0,0 +1,81 @@
+/*!
+ * Module dependencies.
+ */
+
+var MongooseError = require('../error.js');
+
+/**
+ * Schema validator error
+ *
+ * @param {Object} properties
+ * @inherits MongooseError
+ * @api private
+ */
+
+function ValidatorError(properties) {
+ var msg = properties.message;
+ if (!msg) {
+ msg = MongooseError.messages.general.default;
+ }
+
+ var message = this.formatMessage(msg, properties);
+ MongooseError.call(this, message);
+ if (Error.captureStackTrace) {
+ Error.captureStackTrace(this);
+ } else {
+ this.stack = new Error().stack;
+ }
+ this.properties = properties;
+ 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;
+
+/*!
+ * The object used to define this validator. Not enumerable to hide
+ * it from `require('util').inspect()` output re: gh-3925
+ */
+
+Object.defineProperty(ValidatorError.prototype, 'properties', {
+ enumerable: false,
+ writable: true,
+ value: null
+});
+
+/*!
+ * 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;
diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/error/version.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/error/version.js
new file mode 100644
index 0000000..e509b9b
--- /dev/null
+++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/error/version.js
@@ -0,0 +1,33 @@
+'use strict';
+
+/*!
+ * Module dependencies.
+ */
+
+var MongooseError = require('../error.js');
+
+/**
+ * Version Error constructor.
+ *
+ * @inherits MongooseError
+ * @api private
+ */
+
+function VersionError(doc) {
+ MongooseError.call(this, 'No matching document found for id "' + doc._id +
+ '"');
+ this.name = 'VersionError';
+}
+
+/*!
+ * Inherits from MongooseError.
+ */
+
+VersionError.prototype = Object.create(MongooseError.prototype);
+VersionError.prototype.constructor = MongooseError;
+
+/*!
+ * exports
+ */
+
+module.exports = VersionError;
diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/index.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/index.js
new file mode 100644
index 0000000..e0c6445
--- /dev/null
+++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/index.js
@@ -0,0 +1,818 @@
+'use strict';
+
+/*!
+ * Module dependencies.
+ */
+
+var Schema = require('./schema'),
+ SchemaType = require('./schematype'),
+ VirtualType = require('./virtualtype'),
+ STATES = require('./connectionstate'),
+ Types = require('./types'),
+ Query = require('./query'),
+ Model = require('./model'),
+ Document = require('./document'),
+ utils = require('./utils'),
+ format = utils.toCollectionName,
+ pkg = require('../package.json');
+
+var querystring = require('querystring');
+
+var Aggregate = require('./aggregate');
+var PromiseProvider = require('./promise_provider');
+
+/**
+ * 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
+ *
+ * mongoose.set('debug', function(collectionName, methodName, arg1, arg2...) {}); // use custom function to log collection methods + arguments
+ *
+ * @param {String} key
+ * @param {String|Function} value
+ * @api public
+ */
+
+Mongoose.prototype.set = function(key, value) {
+ if (arguments.length === 1) {
+ return this.options[key];
+ }
+
+ this.options[key] = value;
+ return this;
+};
+Mongoose.prototype.set.$hasSideEffects = true;
+
+/**
+ * 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
+ * @param {Object} [options.config] mongoose-specific options
+ * @param {Boolean} [options.config.autoIndex] set to false to disable automatic index creation for all models associated with this connection.
+ * @see Connection#open #connection_Connection-open
+ * @see Connection#openSet #connection_Connection-openSet
+ * @return {Connection} the created Connection object
+ * @api public
+ */
+
+Mongoose.prototype.createConnection = function(uri, options) {
+ var conn = new Connection(this);
+ this.connections.push(conn);
+
+ var rsOption = options && (options.replset || options.replSet);
+ if (arguments.length) {
+ if (rgxReplSet.test(arguments[0]) || checkReplicaSetInUri(arguments[0])) {
+ conn.openSet.apply(conn, arguments).catch(function() {});
+ } else if (rsOption &&
+ (rsOption.replicaSet || rsOption.rs_name)) {
+ conn.openSet.apply(conn, arguments).catch(function() {});
+ } else {
+ conn.open.apply(conn, arguments).catch(function() {});
+ }
+ }
+
+ return conn;
+};
+Mongoose.prototype.createConnection.$hasSideEffects = true;
+
+/**
+ * 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,anotherhost:port,yetanother:port/mydatabase';
+ * 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);
+ *
+ * // optional callback that gets fired when initial connection completed
+ * var uri = 'mongodb://nonexistent.domain:27000';
+ * mongoose.connect(uri, function(error) {
+ * // if error is truthy, the initial connection failed.
+ * })
+ *
+ * @param {String} uri(s)
+ * @param {Object} [options]
+ * @param {Function} [callback]
+ * @see Mongoose#createConnection #index_Mongoose-createConnection
+ * @api public
+ * @return {MongooseThenable} pseudo-promise wrapper around this
+ */
+
+Mongoose.prototype.connect = function() {
+ var conn = this.connection;
+ if (rgxReplSet.test(arguments[0]) || checkReplicaSetInUri(arguments[0])) {
+ return new MongooseThenable(this, conn.openSet.apply(conn, arguments));
+ }
+
+ return new MongooseThenable(this, conn.open.apply(conn, arguments));
+};
+Mongoose.prototype.connect.$hasSideEffects = true;
+
+/**
+ * Disconnects all connections.
+ *
+ * @param {Function} [fn] called after all connection close.
+ * @return {MongooseThenable} pseudo-promise wrapper around this
+ * @api public
+ */
+
+Mongoose.prototype.disconnect = function(fn) {
+ var error;
+ this.connections.forEach(function(conn) {
+ conn.close(function(err) {
+ if (error) {
+ return;
+ }
+ if (err) {
+ error = err;
+ }
+ });
+ });
+
+ var Promise = PromiseProvider.get();
+ return new MongooseThenable(this, new Promise.ES6(function(resolve, reject) {
+ fn && fn(error);
+ if (error) {
+ reject(error);
+ return;
+ }
+ resolve();
+ }));
+};
+Mongoose.prototype.disconnect.$hasSideEffects = true;
+
+/**
+ * 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|Function} name model name or class extending Model
+ * @param {Schema} [schema]
+ * @param {String} [collection] name (optional, inferred from model name)
+ * @param {Boolean} [skipInit] whether to skip initialization (defaults to false)
+ * @api public
+ */
+
+Mongoose.prototype.model = function(name, schema, collection, skipInit) {
+ var model;
+ if (typeof name === 'function') {
+ model = name;
+ name = model.name;
+ if (!(model.prototype instanceof Model)) {
+ throw new mongoose.Error('The provided class ' + name + ' must extend Model');
+ }
+ }
+
+ if (typeof schema === 'string') {
+ collection = schema;
+ schema = false;
+ }
+
+ if (utils.isObject(schema) && !(schema.instanceOfSchema)) {
+ schema = new Schema(schema);
+ }
+ if (schema && !schema.instanceOfSchema) {
+ throw new Error('The 2nd parameter to `mongoose.model()` should be a ' +
+ 'schema or a POJO');
+ }
+
+ if (typeof collection === 'boolean') {
+ 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;
+ } else {
+ throw new mongoose.Error.MissingSchemaError(name);
+ }
+ }
+
+ if (schema) {
+ this._applyPlugins(schema);
+ }
+
+ 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] && options.cache !== false) {
+ if (schema && schema.instanceOfSchema && 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 = this.Model.compile(model || name, schema, collection, connection, this);
+
+ if (!skipInit) {
+ model.init();
+ }
+
+ if (options.cache === false) {
+ return model;
+ }
+
+ this.models[name] = model;
+ return this.models[name];
+};
+Mongoose.prototype.model.$hasSideEffects = true;
+
+/**
+ * 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;
+};
+Mongoose.prototype.modelNames.$hasSideEffects = true;
+
+/**
+ * Applies global plugins to `schema`.
+ *
+ * @param {Schema} schema
+ * @api private
+ */
+
+Mongoose.prototype._applyPlugins = function(schema) {
+ if (schema.$globalPluginsApplied) {
+ return;
+ }
+ var i;
+ var len;
+ for (i = 0, len = this.plugins.length; i < len; ++i) {
+ schema.plugin(this.plugins[i][0], this.plugins[i][1]);
+ }
+ schema.$globalPluginsApplied = true;
+ for (i = 0, len = schema.childSchemas.length; i < len; ++i) {
+ this._applyPlugins(schema.childSchemas[i]);
+ }
+};
+Mongoose.prototype._applyPlugins.$hasSideEffects = true;
+
+/**
+ * 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;
+};
+Mongoose.prototype.plugin.$hasSideEffects = true;
+
+/**
+ * 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];
+});
+
+Mongoose.prototype.__defineSetter__('connection', function(v) {
+ this.connections[0] = v;
+});
+
+/*!
+ * Driver depentend APIs
+ */
+
+var driver = global.MONGOOSE_DRIVER_PATH || './drivers/node-mongodb-native';
+
+/*!
+ * Connection
+ */
+
+var Connection = require(driver + '/connection');
+
+/*!
+ * Collection
+ */
+
+var Collection = require(driver + '/collection');
+
+/**
+ * The Mongoose Aggregate constructor
+ *
+ * @method Aggregate
+ * @api public
+ */
+
+Mongoose.prototype.Aggregate = Aggregate;
+
+/**
+ * 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
+ */
+
+Object.defineProperty(Mongoose.prototype, 'Promise', {
+ get: function() {
+ return PromiseProvider.get();
+ },
+ set: function(lib) {
+ PromiseProvider.set(lib);
+ }
+});
+
+/**
+ * Storage layer for mongoose promises
+ *
+ * @method PromiseProvider
+ * @api public
+ */
+
+Mongoose.prototype.PromiseProvider = PromiseProvider;
+
+/**
+ * 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 Mongoose DocumentProvider constructor.
+ *
+ * @method DocumentProvider
+ * @api public
+ */
+
+Mongoose.prototype.DocumentProvider = require('./document_provider');
+
+/**
+ * The [MongooseError](#error_MongooseError) constructor.
+ *
+ * @method Error
+ * @api public
+ */
+
+Mongoose.prototype.Error = require('./error');
+
+/**
+ * The Mongoose CastError constructor
+ *
+ * @method CastError
+ * @param {String} type The name of the type
+ * @param {Any} value The value that failed to cast
+ * @param {String} path The path `a.b.c` in the doc where this cast error occurred
+ * @param {Error} [reason] The original error that was thrown
+ * @api public
+ */
+
+Mongoose.prototype.CastError = require('./error/cast');
+
+/**
+ * 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');
+
+/**
+ * Wraps the given Mongoose instance into a thenable (pseudo-promise). This
+ * is so `connect()` and `disconnect()` can return a thenable while maintaining
+ * backwards compatibility.
+ *
+ * @api private
+ */
+
+function MongooseThenable(mongoose, promise) {
+ var _this = this;
+ for (var key in mongoose) {
+ if (typeof mongoose[key] === 'function' && mongoose[key].$hasSideEffects) {
+ (function(key) {
+ _this[key] = function() {
+ return mongoose[key].apply(mongoose, arguments);
+ };
+ })(key);
+ } else if (['connection', 'connections'].indexOf(key) !== -1) {
+ _this[key] = mongoose[key];
+ }
+ }
+ this.$opPromise = promise;
+}
+
+MongooseThenable.prototype = new Mongoose;
+
+/**
+ * Ability to use mongoose object as a pseudo-promise so `.connect().then()`
+ * and `.disconnect().then()` are viable.
+ *
+ * @param {Function} onFulfilled
+ * @param {Function} onRejected
+ * @return {Promise}
+ * @api private
+ */
+
+MongooseThenable.prototype.then = function(onFulfilled, onRejected) {
+ var Promise = PromiseProvider.get();
+ if (!this.$opPromise) {
+ return new Promise.ES6(function(resolve, reject) {
+ reject(new Error('Can only call `.then()` if connect() or disconnect() ' +
+ 'has been called'));
+ }).then(onFulfilled, onRejected);
+ }
+ this.$opPromise.$hasHandler = true;
+ return this.$opPromise.then(onFulfilled, onRejected);
+};
+
+/**
+ * Ability to use mongoose object as a pseudo-promise so `.connect().then()`
+ * and `.disconnect().then()` are viable.
+ *
+ * @param {Function} onFulfilled
+ * @param {Function} onRejected
+ * @return {Promise}
+ * @api private
+ */
+
+MongooseThenable.prototype.catch = function(onRejected) {
+ return this.then(null, onRejected);
+};
+
+/*!
+ * The exports object is an instance of Mongoose.
+ *
+ * @api public
+ */
+
+var mongoose = module.exports = exports = new Mongoose;
diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/internal.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/internal.js
new file mode 100644
index 0000000..edf3338
--- /dev/null
+++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/internal.js
@@ -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;
+}
diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/model.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/model.js
new file mode 100644
index 0000000..4a7cbc4
--- /dev/null
+++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/model.js
@@ -0,0 +1,3414 @@
+/*!
+ * Module dependencies.
+ */
+
+var Document = require('./document');
+var MongooseError = require('./error');
+var VersionError = MongooseError.VersionError;
+var DivergentArrayError = MongooseError.DivergentArrayError;
+var Query = require('./query');
+var Aggregate = require('./aggregate');
+var Schema = require('./schema');
+var utils = require('./utils');
+var hasOwnProperty = utils.object.hasOwnProperty;
+var isMongooseObject = utils.isMongooseObject;
+var EventEmitter = require('events').EventEmitter;
+var MongooseArray = require('./types/array');
+var util = require('util');
+var tick = utils.tick;
+
+var parallel = require('async/parallel');
+var PromiseProvider = require('./promise_provider');
+
+var VERSION_WHERE = 1,
+ VERSION_INC = 2,
+ VERSION_ALL = VERSION_WHERE | VERSION_INC;
+
+var POJO_TO_OBJECT_OPTIONS = {
+ depopulate: true,
+ transform: false,
+ _skipDepopulateTopLevel: true
+};
+
+/**
+ * Model constructor
+ *
+ * Provides the interface to MongoDB collections as well as creates document instances.
+ *
+ * @param {Object} doc values with which to create the document
+ * @inherits Document http://mongoosejs.com/docs/api.html#document-js
+ * @event `error`: If listening to this event, it is emitted when a document was saved without passing a callback and an `error` occurred. If not listening, the event bubbles to the connection used to create this Model.
+ * @event `index`: Emitted after `Model#ensureIndexes` completes. If an error occurred it is passed with the event.
+ * @event `index-single-start`: Emitted when an individual index starts within `Model#ensureIndexes`. The fields and options being used to build the index are also passed with the event.
+ * @event `index-single-done`: Emitted when an individual index finishes within `Model#ensureIndexes`. If an error occurred it is passed with the event. The fields, options, and index name are also passed.
+ * @api public
+ */
+
+function Model(doc, fields, skipId) {
+ Document.call(this, doc, fields, skipId);
+}
+
+/*!
+ * Inherits from Document.
+ *
+ * All Model.prototype features are available on
+ * top level (non-sub) documents.
+ */
+
+Model.prototype.__proto__ = Document.prototype;
+
+/**
+ * Connection the model uses.
+ *
+ * @api public
+ * @property db
+ */
+
+Model.prototype.db;
+
+/**
+ * Collection the model uses.
+ *
+ * @api public
+ * @property collection
+ */
+
+Model.prototype.collection;
+
+/**
+ * The name of the model
+ *
+ * @api public
+ * @property modelName
+ */
+
+Model.prototype.modelName;
+
+/**
+ * If this is a discriminator model, `baseModelName` is the name of
+ * the base model.
+ *
+ * @api public
+ * @property baseModelName
+ */
+
+Model.prototype.baseModelName;
+
+Model.prototype.$__handleSave = function(options, callback) {
+ var _this = this;
+ if (!options.safe && this.schema.options.safe) {
+ options.safe = this.schema.options.safe;
+ }
+ if (typeof options.safe === 'boolean') {
+ options.safe = null;
+ }
+
+ if (this.isNew) {
+ // send entire doc
+ var toObjectOptions = {};
+
+ toObjectOptions.retainKeyOrder = this.schema.options.retainKeyOrder;
+ toObjectOptions.depopulate = 1;
+ toObjectOptions._skipDepopulateTopLevel = true;
+ toObjectOptions.transform = false;
+
+ var obj = this.toObject(toObjectOptions);
+
+ if (!utils.object.hasOwnProperty(obj || {}, '_id')) {
+ // documents must have an _id else mongoose won't know
+ // what to update later if more changes are made. the user
+ // wouldn't know what _id was generated by mongodb either
+ // nor would the ObjectId generated my mongodb necessarily
+ // match the schema definition.
+ setTimeout(function() {
+ callback(new Error('document must have an _id before saving'));
+ }, 0);
+ return;
+ }
+
+ this.$__version(true, obj);
+ this.collection.insert(obj, options.safe, function(err, ret) {
+ if (err) {
+ _this.isNew = true;
+ _this.emit('isNew', true);
+
+ callback(err);
+ return;
+ }
+
+ callback(null, ret);
+ });
+ this.$__reset();
+ this.isNew = false;
+ this.emit('isNew', false);
+ // Make it possible to retry the insert
+ this.$__.inserting = true;
+ } else {
+ // Make sure we don't treat it as a new object on error,
+ // since it already exists
+ this.$__.inserting = false;
+
+ var delta = this.$__delta();
+
+ if (delta) {
+ if (delta instanceof Error) {
+ callback(delta);
+ return;
+ }
+
+ var where = this.$__where(delta[0]);
+
+ if (where instanceof Error) {
+ callback(where);
+ return;
+ }
+
+ this.collection.update(where, delta[1], options.safe, function(err, ret) {
+ if (err) {
+ callback(err);
+ return;
+ }
+ callback(null, ret);
+ });
+ } else {
+ this.$__reset();
+ callback();
+ return;
+ }
+
+ this.emit('isNew', false);
+ }
+};
+
+/*!
+ * ignore
+ */
+
+Model.prototype.$__save = function(options, callback) {
+ var _this = this;
+
+ _this.$__handleSave(options, function(error, result) {
+ if (error) {
+ return _this.schema.s.hooks.execPost('save:error', _this, [_this], { error: error }, function(error) {
+ callback(error);
+ });
+ }
+
+ _this.$__reset();
+ _this.$__storeShard();
+
+ var numAffected = 0;
+ if (result) {
+ if (Array.isArray(result)) {
+ numAffected = result.length;
+ } else if (result.result && result.result.n !== undefined) {
+ numAffected = result.result.n;
+ } else if (result.result && result.result.nModified !== undefined) {
+ numAffected = result.result.nModified;
+ } else {
+ numAffected = result;
+ }
+ }
+
+ // was this an update that required a version bump?
+ if (_this.$__.version && !_this.$__.inserting) {
+ var doIncrement = VERSION_INC === (VERSION_INC & _this.$__.version);
+ _this.$__.version = undefined;
+
+ if (numAffected <= 0) {
+ // the update failed. pass an error back
+ var err = new VersionError(_this);
+ return callback(err);
+ }
+
+ // increment version if was successful
+ if (doIncrement) {
+ var key = _this.schema.options.versionKey;
+ var version = _this.getValue(key) | 0;
+ _this.setValue(key, version + 1);
+ }
+ }
+
+ _this.emit('save', _this, numAffected);
+ callback(null, _this, numAffected);
+ });
+};
+
+/**
+ * Saves this document.
+ *
+ * ####Example:
+ *
+ * product.sold = Date.now();
+ * product.save(function (err, product, numAffected) {
+ * if (err) ..
+ * })
+ *
+ * The callback will receive three parameters
+ *
+ * 1. `err` if an error occurred
+ * 2. `product` which is the saved `product`
+ * 3. `numAffected` will be 1 when the document was successfully persisted to MongoDB, otherwise 0. Unless you tweak mongoose's internals, you don't need to worry about checking this parameter for errors - checking `err` is sufficient to make sure your document was properly saved.
+ *
+ * As an extra measure of flow control, save will return a Promise.
+ * ####Example:
+ * product.save().then(function(product) {
+ * ...
+ * });
+ *
+ * For legacy reasons, mongoose stores object keys in reverse order on initial
+ * save. That is, `{ a: 1, b: 2 }` will be saved as `{ b: 2, a: 1 }` in
+ * MongoDB. To override this behavior, set
+ * [the `toObject.retainKeyOrder` option](http://mongoosejs.com/docs/api.html#document_Document-toObject)
+ * to true on your schema.
+ *
+ * @param {Object} [options] options optional options
+ * @param {Object} [options.safe] overrides [schema's safe option](http://mongoosejs.com//docs/guide.html#safe)
+ * @param {Boolean} [options.validateBeforeSave] set to false to save without validating.
+ * @param {Function} [fn] optional callback
+ * @return {Promise} Promise
+ * @api public
+ * @see middleware http://mongoosejs.com/docs/middleware.html
+ */
+
+Model.prototype.save = function(options, fn) {
+ if (typeof options === 'function') {
+ fn = options;
+ options = undefined;
+ }
+
+ if (!options) {
+ options = {};
+ }
+
+ if (fn) {
+ fn = this.constructor.$wrapCallback(fn);
+ }
+
+ return this.$__save(options, fn);
+};
+
+/*!
+ * Determines whether versioning should be skipped for the given path
+ *
+ * @param {Document} self
+ * @param {String} path
+ * @return {Boolean} true if versioning should be skipped for the given path
+ */
+function shouldSkipVersioning(self, path) {
+ var skipVersioning = self.schema.options.skipVersioning;
+ if (!skipVersioning) return false;
+
+ // Remove any array indexes from the path
+ path = path.replace(/\.\d+\./, '.');
+
+ return skipVersioning[path];
+}
+
+/*!
+ * Apply the operation to the delta (update) clause as
+ * well as track versioning for our where clause.
+ *
+ * @param {Document} self
+ * @param {Object} where
+ * @param {Object} delta
+ * @param {Object} data
+ * @param {Mixed} val
+ * @param {String} [operation]
+ */
+
+function operand(self, where, delta, data, val, op) {
+ // delta
+ op || (op = '$set');
+ if (!delta[op]) delta[op] = {};
+ delta[op][data.path] = val;
+
+ // disabled versioning?
+ if (self.schema.options.versionKey === false) return;
+
+ // path excluded from versioning?
+ if (shouldSkipVersioning(self, data.path)) return;
+
+ // already marked for versioning?
+ if (VERSION_ALL === (VERSION_ALL & self.$__.version)) return;
+
+ switch (op) {
+ case '$set':
+ case '$unset':
+ case '$pop':
+ case '$pull':
+ case '$pullAll':
+ case '$push':
+ case '$pushAll':
+ case '$addToSet':
+ break;
+ default:
+ // nothing to do
+ return;
+ }
+
+ // ensure updates sent with positional notation are
+ // editing the correct array element.
+ // only increment the version if an array position changes.
+ // modifying elements of an array is ok if position does not change.
+
+ if (op === '$push' || op === '$pushAll' || op === '$addToSet') {
+ self.$__.version = VERSION_INC;
+ } else if (/^\$p/.test(op)) {
+ // potentially changing array positions
+ self.increment();
+ } else if (Array.isArray(val)) {
+ // $set an array
+ self.increment();
+ } else if (/\.\d+\.|\.\d+$/.test(data.path)) {
+ // now handling $set, $unset
+ // subpath of array
+ self.$__.version = VERSION_WHERE;
+ }
+}
+
+/*!
+ * Compiles an update and where clause for a `val` with _atomics.
+ *
+ * @param {Document} self
+ * @param {Object} where
+ * @param {Object} delta
+ * @param {Object} data
+ * @param {Array} value
+ */
+
+function handleAtomics(self, where, delta, data, value) {
+ if (delta.$set && delta.$set[data.path]) {
+ // $set has precedence over other atomics
+ return;
+ }
+
+ if (typeof value.$__getAtomics === 'function') {
+ value.$__getAtomics().forEach(function(atomic) {
+ var op = atomic[0];
+ var val = atomic[1];
+ if (self.schema.options.usePushEach && op === '$pushAll') {
+ op = '$push';
+ val = { $each: val };
+ }
+ operand(self, where, delta, data, val, op);
+ });
+ return;
+ }
+
+ // legacy support for plugins
+
+ var atomics = value._atomics,
+ ops = Object.keys(atomics),
+ i = ops.length,
+ val,
+ op;
+
+ if (i === 0) {
+ // $set
+
+ if (isMongooseObject(value)) {
+ value = value.toObject({depopulate: 1, _isNested: true});
+ } else if (value.valueOf) {
+ value = value.valueOf();
+ }
+
+ return operand(self, where, delta, data, value);
+ }
+
+ function iter(mem) {
+ return isMongooseObject(mem)
+ ? mem.toObject({depopulate: 1, _isNested: true})
+ : mem;
+ }
+
+ while (i--) {
+ op = ops[i];
+ val = atomics[op];
+
+ if (isMongooseObject(val)) {
+ val = val.toObject({depopulate: true, transform: false, _isNested: true});
+ } else if (Array.isArray(val)) {
+ val = val.map(iter);
+ } else if (val.valueOf) {
+ val = val.valueOf();
+ }
+
+ if (op === '$addToSet') {
+ val = {$each: val};
+ }
+
+ operand(self, where, delta, data, val, op);
+ }
+}
+
+/**
+ * Produces a special query document of the modified properties used in updates.
+ *
+ * @api private
+ * @method $__delta
+ * @memberOf Model
+ */
+
+Model.prototype.$__delta = function() {
+ var dirty = this.$__dirty();
+ if (!dirty.length && VERSION_ALL !== this.$__.version) return;
+
+ var where = {},
+ delta = {},
+ len = dirty.length,
+ divergent = [],
+ d = 0;
+
+ where._id = this._doc._id;
+ if (where._id.toObject) {
+ where._id = where._id.toObject({ transform: false, depopulate: true });
+ }
+
+ for (; d < len; ++d) {
+ var data = dirty[d];
+ var value = data.value;
+
+ var match = checkDivergentArray(this, data.path, value);
+ if (match) {
+ divergent.push(match);
+ continue;
+ }
+
+ var pop = this.populated(data.path, true);
+ if (!pop && this.$__.selected) {
+ // If any array was selected using an $elemMatch projection, we alter the path and where clause
+ // NOTE: MongoDB only supports projected $elemMatch on top level array.
+ var pathSplit = data.path.split('.');
+ var top = pathSplit[0];
+ if (this.$__.selected[top] && this.$__.selected[top].$elemMatch) {
+ // If the selected array entry was modified
+ if (pathSplit.length > 1 && pathSplit[1] == 0 && typeof where[top] === 'undefined') {
+ where[top] = this.$__.selected[top];
+ pathSplit[1] = '$';
+ data.path = pathSplit.join('.');
+ }
+ // if the selected array was modified in any other way throw an error
+ else {
+ divergent.push(data.path);
+ continue;
+ }
+ }
+ }
+
+ if (divergent.length) continue;
+
+ if (undefined === value) {
+ operand(this, where, delta, data, 1, '$unset');
+ } else if (value === null) {
+ operand(this, where, delta, data, null);
+ } else if (value._path && value._atomics) {
+ // arrays and other custom types (support plugins etc)
+ handleAtomics(this, where, delta, data, value);
+ } else if (value._path && Buffer.isBuffer(value)) {
+ // MongooseBuffer
+ value = value.toObject();
+ operand(this, where, delta, data, value);
+ } else {
+ value = utils.clone(value, {depopulate: 1, _isNested: true});
+ operand(this, where, delta, data, value);
+ }
+ }
+
+ if (divergent.length) {
+ return new DivergentArrayError(divergent);
+ }
+
+ if (this.$__.version) {
+ this.$__version(where, delta);
+ }
+
+ return [where, delta];
+};
+
+/*!
+ * Determine if array was populated with some form of filter and is now
+ * being updated in a manner which could overwrite data unintentionally.
+ *
+ * @see https://github.com/Automattic/mongoose/issues/1334
+ * @param {Document} doc
+ * @param {String} path
+ * @return {String|undefined}
+ */
+
+function checkDivergentArray(doc, path, array) {
+ // see if we populated this path
+ var pop = doc.populated(path, true);
+
+ if (!pop && doc.$__.selected) {
+ // If any array was selected using an $elemMatch projection, we deny the update.
+ // NOTE: MongoDB only supports projected $elemMatch on top level array.
+ var top = path.split('.')[0];
+ if (doc.$__.selected[top + '.$']) {
+ return top;
+ }
+ }
+
+ if (!(pop && array && array.isMongooseArray)) return;
+
+ // If the array was populated using options that prevented all
+ // documents from being returned (match, skip, limit) or they
+ // deselected the _id field, $pop and $set of the array are
+ // not safe operations. If _id was deselected, we do not know
+ // how to remove elements. $pop will pop off the _id from the end
+ // of the array in the db which is not guaranteed to be the
+ // same as the last element we have here. $set of the entire array
+ // would be similarily destructive as we never received all
+ // elements of the array and potentially would overwrite data.
+ var check = pop.options.match ||
+ pop.options.options && hasOwnProperty(pop.options.options, 'limit') || // 0 is not permitted
+ pop.options.options && pop.options.options.skip || // 0 is permitted
+ pop.options.select && // deselected _id?
+ (pop.options.select._id === 0 ||
+ /\s?-_id\s?/.test(pop.options.select));
+
+ if (check) {
+ var atomics = array._atomics;
+ if (Object.keys(atomics).length === 0 || atomics.$set || atomics.$pop) {
+ return path;
+ }
+ }
+}
+
+/**
+ * Appends versioning to the where and update clauses.
+ *
+ * @api private
+ * @method $__version
+ * @memberOf Model
+ */
+
+Model.prototype.$__version = function(where, delta) {
+ var key = this.schema.options.versionKey;
+
+ if (where === true) {
+ // this is an insert
+ if (key) this.setValue(key, delta[key] = 0);
+ return;
+ }
+
+ // updates
+
+ // only apply versioning if our versionKey was selected. else
+ // there is no way to select the correct version. we could fail
+ // fast here and force them to include the versionKey but
+ // thats a bit intrusive. can we do this automatically?
+ if (!this.isSelected(key)) {
+ return;
+ }
+
+ // $push $addToSet don't need the where clause set
+ if (VERSION_WHERE === (VERSION_WHERE & this.$__.version)) {
+ where[key] = this.getValue(key);
+ }
+
+ if (VERSION_INC === (VERSION_INC & this.$__.version)) {
+ if (!delta.$set || typeof delta.$set[key] === 'undefined') {
+ delta.$inc || (delta.$inc = {});
+ delta.$inc[key] = 1;
+ }
+ }
+};
+
+/**
+ * Signal that we desire an increment of this documents version.
+ *
+ * ####Example:
+ *
+ * Model.findById(id, function (err, doc) {
+ * doc.increment();
+ * doc.save(function (err) { .. })
+ * })
+ *
+ * @see versionKeys http://mongoosejs.com/docs/guide.html#versionKey
+ * @api public
+ */
+
+Model.prototype.increment = function increment() {
+ this.$__.version = VERSION_ALL;
+ return this;
+};
+
+/**
+ * Returns a query object which applies shardkeys if they exist.
+ *
+ * @api private
+ * @method $__where
+ * @memberOf Model
+ */
+
+Model.prototype.$__where = function _where(where) {
+ where || (where = {});
+
+ var paths,
+ len;
+
+ if (!where._id) {
+ where._id = this._doc._id;
+ }
+
+ if (this.$__.shardval) {
+ paths = Object.keys(this.$__.shardval);
+ len = paths.length;
+
+ for (var i = 0; i < len; ++i) {
+ where[paths[i]] = this.$__.shardval[paths[i]];
+ }
+ }
+
+ if (this._doc._id == null) {
+ return new Error('No _id found on document!');
+ }
+
+ return where;
+};
+
+/**
+ * Removes this document from the db.
+ *
+ * ####Example:
+ * product.remove(function (err, product) {
+ * if (err) return handleError(err);
+ * Product.findById(product._id, function (err, product) {
+ * console.log(product) // null
+ * })
+ * })
+ *
+ *
+ * As an extra measure of flow control, remove will return a Promise (bound to `fn` if passed) so it could be chained, or hooked to recive errors
+ *
+ * ####Example:
+ * product.remove().then(function (product) {
+ * ...
+ * }).onRejected(function (err) {
+ * assert.ok(err)
+ * })
+ *
+ * @param {function(err,product)} [fn] optional callback
+ * @return {Promise} Promise
+ * @api public
+ */
+
+Model.prototype.remove = function remove(options, fn) {
+ if (typeof options === 'function') {
+ fn = options;
+ options = undefined;
+ }
+
+ if (!options) {
+ options = {};
+ }
+
+ if (this.$__.removing) {
+ if (fn) {
+ this.$__.removing.then(
+ function(res) { fn(null, res); },
+ function(err) { fn(err); });
+ }
+ return this;
+ }
+
+ var _this = this;
+ var Promise = PromiseProvider.get();
+
+ if (fn) {
+ fn = this.constructor.$wrapCallback(fn);
+ }
+
+ this.$__.removing = new Promise.ES6(function(resolve, reject) {
+ var where = _this.$__where();
+ if (where instanceof Error) {
+ reject(where);
+ fn && fn(where);
+ return;
+ }
+
+ if (!options.safe && _this.schema.options.safe) {
+ options.safe = _this.schema.options.safe;
+ }
+
+ _this.collection.remove(where, options, function(err) {
+ if (!err) {
+ _this.emit('remove', _this);
+ resolve(_this);
+ fn && fn(null, _this);
+ return;
+ }
+ reject(err);
+ fn && fn(err);
+ });
+ });
+ return this.$__.removing;
+};
+
+/**
+ * Returns another Model instance.
+ *
+ * ####Example:
+ *
+ * var doc = new Tank;
+ * doc.model('User').findById(id, callback);
+ *
+ * @param {String} name model name
+ * @api public
+ */
+
+Model.prototype.model = function model(name) {
+ return this.db.model(name);
+};
+
+/**
+ * Adds a discriminator type.
+ *
+ * ####Example:
+ *
+ * function BaseSchema() {
+ * Schema.apply(this, arguments);
+ *
+ * this.add({
+ * name: String,
+ * createdAt: Date
+ * });
+ * }
+ * util.inherits(BaseSchema, Schema);
+ *
+ * var PersonSchema = new BaseSchema();
+ * var BossSchema = new BaseSchema({ department: String });
+ *
+ * var Person = mongoose.model('Person', PersonSchema);
+ * var Boss = Person.discriminator('Boss', BossSchema);
+ *
+ * @param {String} name discriminator model name
+ * @param {Schema} schema discriminator model schema
+ * @api public
+ */
+
+Model.discriminator = function discriminator(name, schema) {
+ var CUSTOMIZABLE_DISCRIMINATOR_OPTIONS = {
+ toJSON: true,
+ toObject: true,
+ _id: true,
+ id: true
+ };
+
+ if (!(schema && schema.instanceOfSchema)) {
+ throw new Error('You must pass a valid discriminator Schema');
+ }
+
+ if (this.schema.discriminatorMapping && !this.schema.discriminatorMapping.isRoot) {
+ throw new Error('Discriminator "' + name +
+ '" can only be a discriminator of the root model');
+ }
+
+ var key = this.schema.options.discriminatorKey;
+ if (schema.path(key)) {
+ throw new Error('Discriminator "' + name +
+ '" cannot have field with name "' + key + '"');
+ }
+
+ function merge(schema, baseSchema) {
+ utils.merge(schema, baseSchema);
+
+ var obj = {};
+ obj[key] = {
+ default: name,
+ set: function(newName) {
+ if (newName === name) {
+ return name;
+ }
+ throw new Error('Can\'t set discriminator key "' + key + '"');
+ }
+ };
+ obj[key][schema.options.typeKey] = String;
+ schema.add(obj);
+ schema.discriminatorMapping = {key: key, value: name, isRoot: false};
+
+ if (baseSchema.options.collection) {
+ schema.options.collection = baseSchema.options.collection;
+ }
+
+ var toJSON = schema.options.toJSON;
+ var toObject = schema.options.toObject;
+ var _id = schema.options._id;
+ var id = schema.options.id;
+
+ var keys = Object.keys(schema.options);
+
+ for (var i = 0; i < keys.length; ++i) {
+ var _key = keys[i];
+ if (!CUSTOMIZABLE_DISCRIMINATOR_OPTIONS[_key]) {
+ if (!utils.deepEqual(schema.options[_key], baseSchema.options[_key])) {
+ throw new Error('Can\'t customize discriminator option ' + _key +
+ ' (can only modify ' +
+ Object.keys(CUSTOMIZABLE_DISCRIMINATOR_OPTIONS).join(', ') +
+ ')');
+ }
+ }
+ }
+
+ schema.options = utils.clone(baseSchema.options);
+ if (toJSON) schema.options.toJSON = toJSON;
+ if (toObject) schema.options.toObject = toObject;
+ if (typeof _id !== 'undefined') {
+ schema.options._id = _id;
+ }
+ schema.options.id = id;
+
+ schema.callQueue = baseSchema.callQueue.concat(schema.callQueue.slice(schema._defaultMiddleware.length));
+ schema._requiredpaths = undefined; // reset just in case Schema#requiredPaths() was called on either schema
+ }
+
+ // merges base schema into new discriminator schema and sets new type field.
+ merge(schema, this.schema);
+
+ if (!this.discriminators) {
+ this.discriminators = {};
+ }
+
+ if (!this.schema.discriminatorMapping) {
+ this.schema.discriminatorMapping = {key: key, value: null, isRoot: true};
+ }
+
+ if (this.discriminators[name]) {
+ throw new Error('Discriminator with name "' + name + '" already exists');
+ }
+ if (this.db.models[name]) {
+ throw new MongooseError.OverwriteModelError(name);
+ }
+
+ this.discriminators[name] = this.db.model(name, schema, this.collection.name);
+ this.discriminators[name].prototype.__proto__ = this.prototype;
+ Object.defineProperty(this.discriminators[name], 'baseModelName', {
+ value: this.modelName,
+ configurable: true,
+ writable: false
+ });
+
+ // apply methods and statics
+ applyMethods(this.discriminators[name], schema);
+ applyStatics(this.discriminators[name], schema);
+
+ return this.discriminators[name];
+};
+
+// Model (class) features
+
+/*!
+ * Give the constructor the ability to emit events.
+ */
+
+for (var i in EventEmitter.prototype) {
+ Model[i] = EventEmitter.prototype[i];
+}
+
+/**
+ * Called when the model compiles.
+ *
+ * @api private
+ */
+
+Model.init = function init() {
+ if ((this.schema.options.autoIndex) ||
+ (this.schema.options.autoIndex === null && this.db.config.autoIndex)) {
+ this.ensureIndexes({ __noPromise: true, _automatic: true });
+ }
+
+ this.schema.emit('init', this);
+};
+
+/**
+ * Sends `ensureIndex` commands to mongo for each index declared in the schema.
+ *
+ * ####Example:
+ *
+ * Event.ensureIndexes(function (err) {
+ * if (err) return handleError(err);
+ * });
+ *
+ * After completion, an `index` event is emitted on this `Model` passing an error if one occurred.
+ *
+ * ####Example:
+ *
+ * var eventSchema = new Schema({ thing: { type: 'string', unique: true }})
+ * var Event = mongoose.model('Event', eventSchema);
+ *
+ * Event.on('index', function (err) {
+ * if (err) console.error(err); // error occurred during index creation
+ * })
+ *
+ * _NOTE: It is not recommended that you run this in production. Index creation may impact database performance depending on your load. Use with caution._
+ *
+ * The `ensureIndex` commands are not sent in parallel. This is to avoid the `MongoError: cannot add index with a background operation in progress` error. See [this ticket](https://github.com/Automattic/mongoose/issues/1365) for more information.
+ *
+ * @param {Object} [options] internal options
+ * @param {Function} [cb] optional callback
+ * @return {Promise}
+ * @api public
+ */
+
+Model.ensureIndexes = function ensureIndexes(options, callback) {
+ if (typeof options === 'function') {
+ callback = options;
+ options = null;
+ }
+
+ if (options && options.__noPromise) {
+ _ensureIndexes(this, options, callback);
+ return;
+ }
+
+ if (callback) {
+ callback = this.$wrapCallback(callback);
+ }
+
+ var _this = this;
+ var Promise = PromiseProvider.get();
+ return new Promise.ES6(function(resolve, reject) {
+ _ensureIndexes(_this, options || {}, function(error) {
+ if (error) {
+ callback && callback(error);
+ reject(error);
+ }
+ callback && callback();
+ resolve();
+ });
+ });
+};
+
+function _ensureIndexes(model, options, callback) {
+ var indexes = model.schema.indexes();
+ if (!indexes.length) {
+ setImmediate(function() {
+ callback && callback();
+ });
+ return;
+ }
+ // Indexes are created one-by-one to support how MongoDB < 2.4 deals
+ // with background indexes.
+
+ var done = function(err) {
+ if (err && model.schema.options.emitIndexErrors) {
+ model.emit('error', err);
+ }
+ model.emit('index', err);
+ callback && callback(err);
+ };
+
+ var indexSingleDone = function(err, fields, options, name) {
+ model.emit('index-single-done', err, fields, options, name);
+ };
+ var indexSingleStart = function(fields, options) {
+ model.emit('index-single-start', fields, options);
+ };
+
+ var create = function() {
+ var index = indexes.shift();
+ if (!index) return done();
+
+ var indexFields = index[0];
+ var options = index[1];
+ _handleSafe(options);
+
+ indexSingleStart(indexFields, options);
+
+ model.collection.ensureIndex(indexFields, options, tick(function(err, name) {
+ indexSingleDone(err, indexFields, options, name);
+ if (err) {
+ return done(err);
+ }
+ create();
+ }));
+ };
+
+ setImmediate(function() {
+ // If buffering is off, do this manually.
+ if (options._automatic && !model.collection.collection) {
+ model.collection.addQueue(create, []);
+ } else {
+ create();
+ }
+ });
+}
+
+function _handleSafe(options) {
+ if (options.safe) {
+ if (typeof options.safe === 'boolean') {
+ options.w = options.safe;
+ delete options.safe;
+ }
+ if (typeof options.safe === 'object') {
+ options.w = options.safe.w;
+ options.j = options.safe.j;
+ options.wtimeout = options.safe.wtimeout;
+ delete options.safe;
+ }
+ }
+}
+
+/**
+ * Schema the model uses.
+ *
+ * @property schema
+ * @receiver Model
+ * @api public
+ */
+
+Model.schema;
+
+/*!
+ * Connection instance the model uses.
+ *
+ * @property db
+ * @receiver Model
+ * @api public
+ */
+
+Model.db;
+
+/*!
+ * Collection the model uses.
+ *
+ * @property collection
+ * @receiver Model
+ * @api public
+ */
+
+Model.collection;
+
+/**
+ * Base Mongoose instance the model uses.
+ *
+ * @property base
+ * @receiver Model
+ * @api public
+ */
+
+Model.base;
+
+/**
+ * Registered discriminators for this model.
+ *
+ * @property discriminators
+ * @receiver Model
+ * @api public
+ */
+
+Model.discriminators;
+
+/**
+ * Removes documents from the collection.
+ *
+ * ####Example:
+ *
+ * Comment.remove({ title: 'baby born from alien father' }, function (err) {
+ *
+ * });
+ *
+ * ####Note:
+ *
+ * To remove documents without waiting for a response from MongoDB, do not pass a `callback`, then call `exec` on the returned [Query](#query-js):
+ *
+ * var query = Comment.remove({ _id: id });
+ * query.exec();
+ *
+ * ####Note:
+ *
+ * This method sends a remove command directly to MongoDB, no Mongoose documents are involved. Because no Mongoose documents are involved, _no middleware (hooks) are executed_.
+ *
+ * @param {Object} conditions
+ * @param {Function} [callback]
+ * @return {Query}
+ * @api public
+ */
+
+Model.remove = function remove(conditions, callback) {
+ if (typeof conditions === 'function') {
+ callback = conditions;
+ conditions = {};
+ }
+
+ // get the mongodb collection object
+ var mq = new this.Query(conditions, {}, this, this.collection);
+
+ if (callback) {
+ callback = this.$wrapCallback(callback);
+ }
+
+ return mq.remove(callback);
+};
+
+/**
+ * Finds documents
+ *
+ * The `conditions` are cast to their respective SchemaTypes before the command is sent.
+ *
+ * ####Examples:
+ *
+ * // named john and at least 18
+ * MyModel.find({ name: 'john', age: { $gte: 18 }});
+ *
+ * // executes immediately, passing results to callback
+ * MyModel.find({ name: 'john', age: { $gte: 18 }}, function (err, docs) {});
+ *
+ * // name LIKE john and only selecting the "name" and "friends" fields, executing immediately
+ * MyModel.find({ name: /john/i }, 'name friends', function (err, docs) { })
+ *
+ * // passing options
+ * MyModel.find({ name: /john/i }, null, { skip: 10 })
+ *
+ * // passing options and executing immediately
+ * MyModel.find({ name: /john/i }, null, { skip: 10 }, function (err, docs) {});
+ *
+ * // executing a query explicitly
+ * var query = MyModel.find({ name: /john/i }, null, { skip: 10 })
+ * query.exec(function (err, docs) {});
+ *
+ * // using the promise returned from executing a query
+ * var query = MyModel.find({ name: /john/i }, null, { skip: 10 });
+ * var promise = query.exec();
+ * promise.addBack(function (err, docs) {});
+ *
+ * @param {Object} conditions
+ * @param {Object} [projection] optional fields to return (http://bit.ly/1HotzBo)
+ * @param {Object} [options] optional
+ * @param {Function} [callback]
+ * @return {Query}
+ * @see field selection #query_Query-select
+ * @see promise #promise-js
+ * @api public
+ */
+
+Model.find = function find(conditions, projection, options, callback) {
+ if (typeof conditions === 'function') {
+ callback = conditions;
+ conditions = {};
+ projection = null;
+ options = null;
+ } else if (typeof projection === 'function') {
+ callback = projection;
+ projection = null;
+ options = null;
+ } else if (typeof options === 'function') {
+ callback = options;
+ options = null;
+ }
+
+ var mq = new this.Query({}, {}, this, this.collection);
+ mq.select(projection);
+ mq.setOptions(options);
+ if (this.schema.discriminatorMapping && mq.selectedInclusively()) {
+ mq.select(this.schema.options.discriminatorKey);
+ }
+
+ if (callback) {
+ callback = this.$wrapCallback(callback);
+ }
+
+ return mq.find(conditions, callback);
+};
+
+/**
+ * Finds a single document by its _id field. `findById(id)` is almost*
+ * equivalent to `findOne({ _id: id })`. If you want to query by a document's
+ * `_id`, use `findById()` instead of `findOne()`.
+ *
+ * The `id` is cast based on the Schema before sending the command.
+ *
+ * Note: `findById()` triggers `findOne` hooks.
+ *
+ * * Except for how it treats `undefined`. If you use `findOne()`, you'll see
+ * that `findOne(undefined)` and `findOne({ _id: undefined })` are equivalent
+ * to `findOne({})` and return arbitrary documents. However, mongoose
+ * translates `findById(undefined)` into `findOne({ _id: null })`.
+ *
+ * ####Example:
+ *
+ * // find adventure by id and execute immediately
+ * Adventure.findById(id, function (err, adventure) {});
+ *
+ * // same as above
+ * Adventure.findById(id).exec(callback);
+ *
+ * // select only the adventures name and length
+ * Adventure.findById(id, 'name length', function (err, adventure) {});
+ *
+ * // same as above
+ * Adventure.findById(id, 'name length').exec(callback);
+ *
+ * // include all properties except for `length`
+ * Adventure.findById(id, '-length').exec(function (err, adventure) {});
+ *
+ * // passing options (in this case return the raw js objects, not mongoose documents by passing `lean`
+ * Adventure.findById(id, 'name', { lean: true }, function (err, doc) {});
+ *
+ * // same as above
+ * Adventure.findById(id, 'name').lean().exec(function (err, doc) {});
+ *
+ * @param {Object|String|Number} id value of `_id` to query by
+ * @param {Object} [projection] optional fields to return (http://bit.ly/1HotzBo)
+ * @param {Object} [options] optional
+ * @param {Function} [callback]
+ * @return {Query}
+ * @see field selection #query_Query-select
+ * @see lean queries #query_Query-lean
+ * @api public
+ */
+
+Model.findById = function findById(id, projection, options, callback) {
+ if (typeof id === 'undefined') {
+ id = null;
+ }
+
+ if (callback) {
+ callback = this.$wrapCallback(callback);
+ }
+
+ return this.findOne({_id: id}, projection, options, callback);
+};
+
+/**
+ * Finds one document.
+ *
+ * The `conditions` are cast to their respective SchemaTypes before the command is sent.
+ *
+ * *Note:* `conditions` is optional, and if `conditions` is null or undefined,
+ * mongoose will send an empty `findOne` command to MongoDB, which will return
+ * an arbitrary document. If you're querying by `_id`, use `findById()` instead.
+ *
+ * ####Example:
+ *
+ * // find one iphone adventures - iphone adventures??
+ * Adventure.findOne({ type: 'iphone' }, function (err, adventure) {});
+ *
+ * // same as above
+ * Adventure.findOne({ type: 'iphone' }).exec(function (err, adventure) {});
+ *
+ * // select only the adventures name
+ * Adventure.findOne({ type: 'iphone' }, 'name', function (err, adventure) {});
+ *
+ * // same as above
+ * Adventure.findOne({ type: 'iphone' }, 'name').exec(function (err, adventure) {});
+ *
+ * // specify options, in this case lean
+ * Adventure.findOne({ type: 'iphone' }, 'name', { lean: true }, callback);
+ *
+ * // same as above
+ * Adventure.findOne({ type: 'iphone' }, 'name', { lean: true }).exec(callback);
+ *
+ * // chaining findOne queries (same as above)
+ * Adventure.findOne({ type: 'iphone' }).select('name').lean().exec(callback);
+ *
+ * @param {Object} [conditions]
+ * @param {Object} [projection] optional fields to return (http://bit.ly/1HotzBo)
+ * @param {Object} [options] optional
+ * @param {Function} [callback]
+ * @return {Query}
+ * @see field selection #query_Query-select
+ * @see lean queries #query_Query-lean
+ * @api public
+ */
+
+Model.findOne = function findOne(conditions, projection, options, callback) {
+ if (typeof options === 'function') {
+ callback = options;
+ options = null;
+ } else if (typeof projection === 'function') {
+ callback = projection;
+ projection = null;
+ options = null;
+ } else if (typeof conditions === 'function') {
+ callback = conditions;
+ conditions = {};
+ projection = null;
+ options = null;
+ }
+
+ // get the mongodb collection object
+ var mq = new this.Query({}, {}, this, this.collection);
+ mq.select(projection);
+ mq.setOptions(options);
+ if (this.schema.discriminatorMapping && mq.selectedInclusively()) {
+ mq.select(this.schema.options.discriminatorKey);
+ }
+
+ if (callback) {
+ callback = this.$wrapCallback(callback);
+ }
+
+ return mq.findOne(conditions, callback);
+};
+
+/**
+ * Counts number of matching documents in a database collection.
+ *
+ * ####Example:
+ *
+ * Adventure.count({ type: 'jungle' }, function (err, count) {
+ * if (err) ..
+ * console.log('there are %d jungle adventures', count);
+ * });
+ *
+ * @param {Object} conditions
+ * @param {Function} [callback]
+ * @return {Query}
+ * @api public
+ */
+
+Model.count = function count(conditions, callback) {
+ if (typeof conditions === 'function') {
+ callback = conditions;
+ conditions = {};
+ }
+
+ // get the mongodb collection object
+ var mq = new this.Query({}, {}, this, this.collection);
+
+ if (callback) {
+ callback = this.$wrapCallback(callback);
+ }
+
+ return mq.count(conditions, callback);
+};
+
+/**
+ * Creates a Query for a `distinct` operation.
+ *
+ * Passing a `callback` immediately executes the query.
+ *
+ * ####Example
+ *
+ * Link.distinct('url', { clicks: {$gt: 100}}, function (err, result) {
+ * if (err) return handleError(err);
+ *
+ * assert(Array.isArray(result));
+ * console.log('unique urls with more than 100 clicks', result);
+ * })
+ *
+ * var query = Link.distinct('url');
+ * query.exec(callback);
+ *
+ * @param {String} field
+ * @param {Object} [conditions] optional
+ * @param {Function} [callback]
+ * @return {Query}
+ * @api public
+ */
+
+Model.distinct = function distinct(field, conditions, callback) {
+ // get the mongodb collection object
+ var mq = new this.Query({}, {}, this, this.collection);
+
+ if (typeof conditions === 'function') {
+ callback = conditions;
+ conditions = {};
+ }
+ if (callback) {
+ callback = this.$wrapCallback(callback);
+ }
+
+ return mq.distinct(field, conditions, callback);
+};
+
+/**
+ * Creates a Query, applies the passed conditions, and returns the Query.
+ *
+ * For example, instead of writing:
+ *
+ * User.find({age: {$gte: 21, $lte: 65}}, callback);
+ *
+ * we can instead write:
+ *
+ * User.where('age').gte(21).lte(65).exec(callback);
+ *
+ * Since the Query class also supports `where` you can continue chaining
+ *
+ * User
+ * .where('age').gte(21).lte(65)
+ * .where('name', /^b/i)
+ * ... etc
+ *
+ * @param {String} path
+ * @param {Object} [val] optional value
+ * @return {Query}
+ * @api public
+ */
+
+Model.where = function where(path, val) {
+ void val; // eslint
+ // get the mongodb collection object
+ var mq = new this.Query({}, {}, this, this.collection).find({});
+ return mq.where.apply(mq, arguments);
+};
+
+/**
+ * Creates a `Query` and specifies a `$where` condition.
+ *
+ * Sometimes you need to query for things in mongodb using a JavaScript expression. You can do so via `find({ $where: javascript })`, or you can use the mongoose shortcut method $where via a Query chain or from your mongoose Model.
+ *
+ * Blog.$where('this.username.indexOf("val") !== -1').exec(function (err, docs) {});
+ *
+ * @param {String|Function} argument is a javascript string or anonymous function
+ * @method $where
+ * @memberOf Model
+ * @return {Query}
+ * @see Query.$where #query_Query-%24where
+ * @api public
+ */
+
+Model.$where = function $where() {
+ var mq = new this.Query({}, {}, this, this.collection).find({});
+ return mq.$where.apply(mq, arguments);
+};
+
+/**
+ * Issues a mongodb findAndModify update command.
+ *
+ * Finds a matching document, updates it according to the `update` arg, passing any `options`, and returns the found document (if any) to the callback. The query executes immediately if `callback` is passed else a Query object is returned.
+ *
+ * ####Options:
+ *
+ * - `new`: bool - if true, return the modified document rather than the original. defaults to false (changed in 4.0)
+ * - `upsert`: bool - creates the object if it doesn't exist. defaults to false.
+ * - `fields`: {Object|String} - Field selection. Equivalent to `.select(fields).findOneAndUpdate()`
+ * - `maxTimeMS`: puts a time limit on the query - requires mongodb >= 2.6.0
+ * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update
+ * - `runValidators`: if true, runs [update validators](/docs/validation.html#update-validators) on this command. Update validators validate the update operation against the model's schema.
+ * - `setDefaultsOnInsert`: if this and `upsert` are true, mongoose will apply the [defaults](http://mongoosejs.com/docs/defaults.html) specified in the model's schema if a new document is created. This option only works on MongoDB >= 2.4 because it relies on [MongoDB's `$setOnInsert` operator](https://docs.mongodb.org/v2.4/reference/operator/update/setOnInsert/).
+ * - `passRawResult`: if true, passes the [raw result from the MongoDB driver as the third callback parameter](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify)
+ *
+ *
+ * ####Examples:
+ *
+ * A.findOneAndUpdate(conditions, update, options, callback) // executes
+ * A.findOneAndUpdate(conditions, update, options) // returns Query
+ * A.findOneAndUpdate(conditions, update, callback) // executes
+ * A.findOneAndUpdate(conditions, update) // returns Query
+ * A.findOneAndUpdate() // returns Query
+ *
+ * ####Note:
+ *
+ * All top level update keys which are not `atomic` operation names are treated as set operations:
+ *
+ * ####Example:
+ *
+ * var query = { name: 'borne' };
+ * Model.findOneAndUpdate(query, { name: 'jason borne' }, options, callback)
+ *
+ * // is sent as
+ * Model.findOneAndUpdate(query, { $set: { name: 'jason borne' }}, options, callback)
+ *
+ * This helps prevent accidentally overwriting your document with `{ name: 'jason borne' }`.
+ *
+ * ####Note:
+ *
+ * Values are cast to their appropriate types when using the findAndModify helpers.
+ * However, the below are never executed.
+ *
+ * - defaults
+ * - setters
+ *
+ * `findAndModify` helpers support limited defaults and validation. You can
+ * enable these by setting the `setDefaultsOnInsert` and `runValidators` options,
+ * respectively.
+ *
+ * If you need full-fledged validation, use the traditional approach of first
+ * retrieving the document.
+ *
+ * Model.findById(id, function (err, doc) {
+ * if (err) ..
+ * doc.name = 'jason borne';
+ * doc.save(callback);
+ * });
+ *
+ * @param {Object} [conditions]
+ * @param {Object} [update]
+ * @param {Object} [options]
+ * @param {Function} [callback]
+ * @return {Query}
+ * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command
+ * @api public
+ */
+
+Model.findOneAndUpdate = function(conditions, update, options, callback) {
+ if (typeof options === 'function') {
+ callback = options;
+ options = null;
+ } else if (arguments.length === 1) {
+ if (typeof conditions === 'function') {
+ var msg = 'Model.findOneAndUpdate(): First argument must not be a function.\n\n'
+ + ' ' + this.modelName + '.findOneAndUpdate(conditions, update, options, callback)\n'
+ + ' ' + this.modelName + '.findOneAndUpdate(conditions, update, options)\n'
+ + ' ' + this.modelName + '.findOneAndUpdate(conditions, update)\n'
+ + ' ' + this.modelName + '.findOneAndUpdate(update)\n'
+ + ' ' + this.modelName + '.findOneAndUpdate()\n';
+ throw new TypeError(msg);
+ }
+ update = conditions;
+ conditions = undefined;
+ }
+ if (callback) {
+ callback = this.$wrapCallback(callback);
+ }
+
+ var fields;
+ if (options && options.fields) {
+ fields = options.fields;
+ }
+
+ update = utils.clone(update, {depopulate: 1, _isNested: true});
+ if (this.schema.options.versionKey && options && options.upsert) {
+ if (!update.$setOnInsert) {
+ update.$setOnInsert = {};
+ }
+ update.$setOnInsert[this.schema.options.versionKey] = 0;
+ }
+
+ var mq = new this.Query({}, {}, this, this.collection);
+ mq.select(fields);
+
+ return mq.findOneAndUpdate(conditions, update, options, callback);
+};
+
+/**
+ * Issues a mongodb findAndModify update command by a document's _id field.
+ * `findByIdAndUpdate(id, ...)` is equivalent to `findOneAndUpdate({ _id: id }, ...)`.
+ *
+ * Finds a matching document, updates it according to the `update` arg,
+ * passing any `options`, and returns the found document (if any) to the
+ * callback. The query executes immediately if `callback` is passed else a
+ * Query object is returned.
+ *
+ * This function triggers `findOneAndUpdate` middleware.
+ *
+ * ####Options:
+ *
+ * - `new`: bool - true to return the modified document rather than the original. defaults to false
+ * - `upsert`: bool - creates the object if it doesn't exist. defaults to false.
+ * - `runValidators`: if true, runs [update validators](/docs/validation.html#update-validators) on this command. Update validators validate the update operation against the model's schema.
+ * - `setDefaultsOnInsert`: if this and `upsert` are true, mongoose will apply the [defaults](http://mongoosejs.com/docs/defaults.html) specified in the model's schema if a new document is created. This option only works on MongoDB >= 2.4 because it relies on [MongoDB's `$setOnInsert` operator](https://docs.mongodb.org/v2.4/reference/operator/update/setOnInsert/).
+ * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update
+ * - `select`: sets the document fields to return
+ *
+ * ####Examples:
+ *
+ * A.findByIdAndUpdate(id, update, options, callback) // executes
+ * A.findByIdAndUpdate(id, update, options) // returns Query
+ * A.findByIdAndUpdate(id, update, callback) // executes
+ * A.findByIdAndUpdate(id, update) // returns Query
+ * A.findByIdAndUpdate() // returns Query
+ *
+ * ####Note:
+ *
+ * All top level update keys which are not `atomic` operation names are treated as set operations:
+ *
+ * ####Example:
+ *
+ * Model.findByIdAndUpdate(id, { name: 'jason borne' }, options, callback)
+ *
+ * // is sent as
+ * Model.findByIdAndUpdate(id, { $set: { name: 'jason borne' }}, options, callback)
+ *
+ * This helps prevent accidentally overwriting your document with `{ name: 'jason borne' }`.
+ *
+ * ####Note:
+ *
+ * Values are cast to their appropriate types when using the findAndModify helpers.
+ * However, the below are never executed.
+ *
+ * - defaults
+ * - setters
+ *
+ * `findAndModify` helpers support limited defaults and validation. You can
+ * enable these by setting the `setDefaultsOnInsert` and `runValidators` options,
+ * respectively.
+ *
+ * If you need full-fledged validation, use the traditional approach of first
+ * retrieving the document.
+ *
+ * Model.findById(id, function (err, doc) {
+ * if (err) ..
+ * doc.name = 'jason borne';
+ * doc.save(callback);
+ * });
+ *
+ * @param {Object|Number|String} id value of `_id` to query by
+ * @param {Object} [update]
+ * @param {Object} [options]
+ * @param {Function} [callback]
+ * @return {Query}
+ * @see Model.findOneAndUpdate #model_Model.findOneAndUpdate
+ * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command
+ * @api public
+ */
+
+Model.findByIdAndUpdate = function(id, update, options, callback) {
+ if (callback) {
+ callback = this.$wrapCallback(callback);
+ }
+ if (arguments.length === 1) {
+ if (typeof id === 'function') {
+ var msg = 'Model.findByIdAndUpdate(): First argument must not be a function.\n\n'
+ + ' ' + this.modelName + '.findByIdAndUpdate(id, callback)\n'
+ + ' ' + this.modelName + '.findByIdAndUpdate(id)\n'
+ + ' ' + this.modelName + '.findByIdAndUpdate()\n';
+ throw new TypeError(msg);
+ }
+ return this.findOneAndUpdate({_id: id}, undefined);
+ }
+
+ // if a model is passed in instead of an id
+ if (id instanceof Document) {
+ id = id._id;
+ }
+
+ return this.findOneAndUpdate.call(this, {_id: id}, update, options, callback);
+};
+
+/**
+ * Issue a mongodb findAndModify remove command.
+ *
+ * Finds a matching document, removes it, passing the found document (if any) to the callback.
+ *
+ * Executes immediately if `callback` is passed else a Query object is returned.
+ *
+ * ####Options:
+ *
+ * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update
+ * - `maxTimeMS`: puts a time limit on the query - requires mongodb >= 2.6.0
+ * - `select`: sets the document fields to return
+ *
+ * ####Examples:
+ *
+ * A.findOneAndRemove(conditions, options, callback) // executes
+ * A.findOneAndRemove(conditions, options) // return Query
+ * A.findOneAndRemove(conditions, callback) // executes
+ * A.findOneAndRemove(conditions) // returns Query
+ * A.findOneAndRemove() // returns Query
+ *
+ * Values are cast to their appropriate types when using the findAndModify helpers.
+ * However, the below are never executed.
+ *
+ * - defaults
+ * - setters
+ *
+ * `findAndModify` helpers support limited defaults and validation. You can
+ * enable these by setting the `setDefaultsOnInsert` and `runValidators` options,
+ * respectively.
+ *
+ * If you need full-fledged validation, use the traditional approach of first
+ * retrieving the document.
+ *
+ * Model.findById(id, function (err, doc) {
+ * if (err) ..
+ * doc.name = 'jason borne';
+ * doc.save(callback);
+ * });
+ *
+ * @param {Object} conditions
+ * @param {Object} [options]
+ * @param {Function} [callback]
+ * @return {Query}
+ * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command
+ * @api public
+ */
+
+Model.findOneAndRemove = function(conditions, options, callback) {
+ if (arguments.length === 1 && typeof conditions === 'function') {
+ var msg = 'Model.findOneAndRemove(): First argument must not be a function.\n\n'
+ + ' ' + this.modelName + '.findOneAndRemove(conditions, callback)\n'
+ + ' ' + this.modelName + '.findOneAndRemove(conditions)\n'
+ + ' ' + this.modelName + '.findOneAndRemove()\n';
+ throw new TypeError(msg);
+ }
+
+ if (typeof options === 'function') {
+ callback = options;
+ options = undefined;
+ }
+ if (callback) {
+ callback = this.$wrapCallback(callback);
+ }
+
+ var fields;
+ if (options) {
+ fields = options.select;
+ options.select = undefined;
+ }
+
+ var mq = new this.Query({}, {}, this, this.collection);
+ mq.select(fields);
+
+ return mq.findOneAndRemove(conditions, options, callback);
+};
+
+/**
+ * Issue a mongodb findAndModify remove command by a document's _id field. `findByIdAndRemove(id, ...)` is equivalent to `findOneAndRemove({ _id: id }, ...)`.
+ *
+ * Finds a matching document, removes it, passing the found document (if any) to the callback.
+ *
+ * Executes immediately if `callback` is passed, else a `Query` object is returned.
+ *
+ * ####Options:
+ *
+ * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update
+ * - `select`: sets the document fields to return
+ *
+ * ####Examples:
+ *
+ * A.findByIdAndRemove(id, options, callback) // executes
+ * A.findByIdAndRemove(id, options) // return Query
+ * A.findByIdAndRemove(id, callback) // executes
+ * A.findByIdAndRemove(id) // returns Query
+ * A.findByIdAndRemove() // returns Query
+ *
+ * @param {Object|Number|String} id value of `_id` to query by
+ * @param {Object} [options]
+ * @param {Function} [callback]
+ * @return {Query}
+ * @see Model.findOneAndRemove #model_Model.findOneAndRemove
+ * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command
+ */
+
+Model.findByIdAndRemove = function(id, options, callback) {
+ if (arguments.length === 1 && typeof id === 'function') {
+ var msg = 'Model.findByIdAndRemove(): First argument must not be a function.\n\n'
+ + ' ' + this.modelName + '.findByIdAndRemove(id, callback)\n'
+ + ' ' + this.modelName + '.findByIdAndRemove(id)\n'
+ + ' ' + this.modelName + '.findByIdAndRemove()\n';
+ throw new TypeError(msg);
+ }
+ if (callback) {
+ callback = this.$wrapCallback(callback);
+ }
+
+ return this.findOneAndRemove({_id: id}, options, callback);
+};
+
+/**
+ * Shortcut for saving one or more documents to the database.
+ * `MyModel.create(docs)` does `new MyModel(doc).save()` for every doc in
+ * docs.
+ *
+ * Hooks Triggered:
+ * - `save()`
+ *
+ * ####Example:
+ *
+ * // pass individual docs
+ * Candy.create({ type: 'jelly bean' }, { type: 'snickers' }, function (err, jellybean, snickers) {
+ * if (err) // ...
+ * });
+ *
+ * // pass an array
+ * var array = [{ type: 'jelly bean' }, { type: 'snickers' }];
+ * Candy.create(array, function (err, candies) {
+ * if (err) // ...
+ *
+ * var jellybean = candies[0];
+ * var snickers = candies[1];
+ * // ...
+ * });
+ *
+ * // callback is optional; use the returned promise if you like:
+ * var promise = Candy.create({ type: 'jawbreaker' });
+ * promise.then(function (jawbreaker) {
+ * // ...
+ * })
+ *
+ * @param {Array|Object|*} doc(s)
+ * @param {Function} [callback] callback
+ * @return {Promise}
+ * @api public
+ */
+
+Model.create = function create(doc, callback) {
+ var args;
+ var cb;
+
+ if (Array.isArray(doc)) {
+ args = doc;
+ cb = callback;
+ } else {
+ var last = arguments[arguments.length - 1];
+ if (typeof last === 'function') {
+ cb = last;
+ args = utils.args(arguments, 0, arguments.length - 1);
+ } else {
+ args = utils.args(arguments);
+ }
+ }
+
+ var Promise = PromiseProvider.get();
+ var _this = this;
+ if (cb) {
+ cb = this.$wrapCallback(cb);
+ }
+
+ var promise = new Promise.ES6(function(resolve, reject) {
+ if (args.length === 0) {
+ setImmediate(function() {
+ cb && cb(null);
+ resolve(null);
+ });
+ return;
+ }
+
+ var toExecute = [];
+ args.forEach(function(doc) {
+ toExecute.push(function(callback) {
+ var toSave = doc instanceof _this ? doc : new _this(doc);
+ var callbackWrapper = function(error, doc) {
+ if (error) {
+ return callback(error);
+ }
+ callback(null, doc);
+ };
+
+ // Hack to avoid getting a promise because of
+ // $__registerHooksFromSchema
+ if (toSave.$__original_save) {
+ toSave.$__original_save({ __noPromise: true }, callbackWrapper);
+ } else {
+ toSave.save({ __noPromise: true }, callbackWrapper);
+ }
+ });
+ });
+
+ parallel(toExecute, function(error, savedDocs) {
+ if (error) {
+ if (cb) {
+ cb(error);
+ } else {
+ reject(error);
+ }
+ return;
+ }
+
+ if (doc instanceof Array) {
+ resolve(savedDocs);
+ cb && cb.call(_this, null, savedDocs);
+ } else {
+ resolve.apply(promise, savedDocs);
+ if (cb) {
+ savedDocs.unshift(null);
+ cb.apply(_this, savedDocs);
+ }
+ }
+ });
+ });
+
+ return promise;
+};
+
+/**
+ * Shortcut for validating an array of documents and inserting them into
+ * MongoDB if they're all valid. This function is faster than `.create()`
+ * because it only sends one operation to the server, rather than one for each
+ * document.
+ *
+ * This function does **not** trigger save middleware.
+ *
+ * ####Example:
+ *
+ * var arr = [{ name: 'Star Wars' }, { name: 'The Empire Strikes Back' }];
+ * Movies.insertMany(arr, function(error, docs) {});
+ *
+ * @param {Array|Object|*} doc(s)
+ * @param {Function} [callback] callback
+ * @return {Promise}
+ * @api public
+ */
+
+Model.insertMany = function(arr, callback) {
+ var _this = this;
+ if (callback) {
+ callback = this.$wrapCallback(callback);
+ }
+
+ var toExecute = [];
+ arr.forEach(function(doc) {
+ toExecute.push(function(callback) {
+ doc = new _this(doc);
+ doc.validate({ __noPromise: true }, function(error) {
+ if (error) {
+ return callback(error);
+ }
+ callback(null, doc);
+ });
+ });
+ });
+
+ parallel(toExecute, function(error, docs) {
+ if (error) {
+ callback && callback(error);
+ return;
+ }
+ var docObjects = docs.map(function(doc) {
+ if (doc.schema.options.versionKey) {
+ doc[doc.schema.options.versionKey] = 0;
+ }
+ if (doc.initializeTimestamps) {
+ return doc.initializeTimestamps().toObject(POJO_TO_OBJECT_OPTIONS);
+ }
+ return doc.toObject(POJO_TO_OBJECT_OPTIONS);
+ });
+ _this.collection.insertMany(docObjects, function(error) {
+ if (error) {
+ callback && callback(error);
+ return;
+ }
+ for (var i = 0; i < docs.length; ++i) {
+ docs[i].isNew = false;
+ docs[i].emit('isNew', false);
+ }
+ callback && callback(null, docs);
+ });
+ });
+};
+
+/**
+ * Shortcut for creating a new Document from existing raw data, pre-saved in the DB.
+ * The document returned has no paths marked as modified initially.
+ *
+ * ####Example:
+ *
+ * // hydrate previous data into a Mongoose document
+ * var mongooseCandy = Candy.hydrate({ _id: '54108337212ffb6d459f854c', type: 'jelly bean' });
+ *
+ * @param {Object} obj
+ * @return {Document}
+ * @api public
+ */
+
+Model.hydrate = function(obj) {
+ var model = require('./queryhelpers').createModel(this, obj);
+ model.init(obj);
+ return model;
+};
+
+/**
+ * Updates documents in the database without returning them.
+ *
+ * ####Examples:
+ *
+ * MyModel.update({ age: { $gt: 18 } }, { oldEnough: true }, fn);
+ * MyModel.update({ name: 'Tobi' }, { ferret: true }, { multi: true }, function (err, raw) {
+ * if (err) return handleError(err);
+ * console.log('The raw response from Mongo was ', raw);
+ * });
+ *
+ * ####Valid options:
+ *
+ * - `safe` (boolean) safe mode (defaults to value set in schema (true))
+ * - `upsert` (boolean) whether to create the doc if it doesn't match (false)
+ * - `multi` (boolean) whether multiple documents should be updated (false)
+ * - `runValidators`: if true, runs [update validators](/docs/validation.html#update-validators) on this command. Update validators validate the update operation against the model's schema.
+ * - `setDefaultsOnInsert`: if this and `upsert` are true, mongoose will apply the [defaults](http://mongoosejs.com/docs/defaults.html) specified in the model's schema if a new document is created. This option only works on MongoDB >= 2.4 because it relies on [MongoDB's `$setOnInsert` operator](https://docs.mongodb.org/v2.4/reference/operator/update/setOnInsert/).
+ * - `strict` (boolean) overrides the `strict` option for this update
+ * - `overwrite` (boolean) disables update-only mode, allowing you to overwrite the doc (false)
+ *
+ * All `update` values are cast to their appropriate SchemaTypes before being sent.
+ *
+ * The `callback` function receives `(err, rawResponse)`.
+ *
+ * - `err` is the error if any occurred
+ * - `rawResponse` is the full response from Mongo
+ *
+ * ####Note:
+ *
+ * All top level keys which are not `atomic` operation names are treated as set operations:
+ *
+ * ####Example:
+ *
+ * var query = { name: 'borne' };
+ * Model.update(query, { name: 'jason borne' }, options, callback)
+ *
+ * // is sent as
+ * Model.update(query, { $set: { name: 'jason borne' }}, options, callback)
+ * // if overwrite option is false. If overwrite is true, sent without the $set wrapper.
+ *
+ * This helps prevent accidentally overwriting all documents in your collection with `{ name: 'jason borne' }`.
+ *
+ * ####Note:
+ *
+ * Be careful to not use an existing model instance for the update clause (this won't work and can cause weird behavior like infinite loops). Also, ensure that the update clause does not have an _id property, which causes Mongo to return a "Mod on _id not allowed" error.
+ *
+ * ####Note:
+ *
+ * To update documents without waiting for a response from MongoDB, do not pass a `callback`, then call `exec` on the returned [Query](#query-js):
+ *
+ * Comment.update({ _id: id }, { $set: { text: 'changed' }}).exec();
+ *
+ * ####Note:
+ *
+ * Although values are casted to their appropriate types when using update, the following are *not* applied:
+ *
+ * - defaults
+ * - setters
+ * - validators
+ * - middleware
+ *
+ * If you need those features, use the traditional approach of first retrieving the document.
+ *
+ * Model.findOne({ name: 'borne' }, function (err, doc) {
+ * if (err) ..
+ * doc.name = 'jason borne';
+ * doc.save(callback);
+ * })
+ *
+ * @see strict http://mongoosejs.com/docs/guide.html#strict
+ * @see response http://docs.mongodb.org/v2.6/reference/command/update/#output
+ * @param {Object} conditions
+ * @param {Object} doc
+ * @param {Object} [options]
+ * @param {Function} [callback]
+ * @return {Query}
+ * @api public
+ */
+
+Model.update = function update(conditions, doc, options, callback) {
+ var mq = new this.Query({}, {}, this, this.collection);
+ if (callback) {
+ callback = this.$wrapCallback(callback);
+ }
+ // gh-2406
+ // make local deep copy of conditions
+ if (conditions instanceof Document) {
+ conditions = conditions.toObject();
+ } else {
+ conditions = utils.clone(conditions, {retainKeyOrder: true});
+ }
+ options = typeof options === 'function' ? options : utils.clone(options);
+
+ if (this.schema.options.versionKey && options && options.upsert) {
+ if (!doc.$setOnInsert) {
+ doc.$setOnInsert = {};
+ }
+ doc.$setOnInsert[this.schema.options.versionKey] = 0;
+ }
+
+ return mq.update(conditions, doc, options, callback);
+};
+
+/**
+ * Executes a mapReduce command.
+ *
+ * `o` is an object specifying all mapReduce options as well as the map and reduce functions. All options are delegated to the driver implementation. See [node-mongodb-native mapReduce() documentation](http://mongodb.github.io/node-mongodb-native/api-generated/collection.html#mapreduce) for more detail about options.
+ *
+ * ####Example:
+ *
+ * var o = {};
+ * o.map = function () { emit(this.name, 1) }
+ * o.reduce = function (k, vals) { return vals.length }
+ * User.mapReduce(o, function (err, results) {
+ * console.log(results)
+ * })
+ *
+ * ####Other options:
+ *
+ * - `query` {Object} query filter object.
+ * - `sort` {Object} sort input objects using this key
+ * - `limit` {Number} max number of documents
+ * - `keeptemp` {Boolean, default:false} keep temporary data
+ * - `finalize` {Function} finalize function
+ * - `scope` {Object} scope variables exposed to map/reduce/finalize during execution
+ * - `jsMode` {Boolean, default:false} it is possible to make the execution stay in JS. Provided in MongoDB > 2.0.X
+ * - `verbose` {Boolean, default:false} provide statistics on job execution time.
+ * - `readPreference` {String}
+ * - `out*` {Object, default: {inline:1}} sets the output target for the map reduce job.
+ *
+ * ####* out options:
+ *
+ * - `{inline:1}` the results are returned in an array
+ * - `{replace: 'collectionName'}` add the results to collectionName: the results replace the collection
+ * - `{reduce: 'collectionName'}` add the results to collectionName: if dups are detected, uses the reducer / finalize functions
+ * - `{merge: 'collectionName'}` add the results to collectionName: if dups exist the new docs overwrite the old
+ *
+ * If `options.out` is set to `replace`, `merge`, or `reduce`, a Model instance is returned that can be used for further querying. Queries run against this model are all executed with the `lean` option; meaning only the js object is returned and no Mongoose magic is applied (getters, setters, etc).
+ *
+ * ####Example:
+ *
+ * var o = {};
+ * o.map = function () { emit(this.name, 1) }
+ * o.reduce = function (k, vals) { return vals.length }
+ * o.out = { replace: 'createdCollectionNameForResults' }
+ * o.verbose = true;
+ *
+ * User.mapReduce(o, function (err, model, stats) {
+ * console.log('map reduce took %d ms', stats.processtime)
+ * model.find().where('value').gt(10).exec(function (err, docs) {
+ * console.log(docs);
+ * });
+ * })
+ *
+ * // a promise is returned so you may instead write
+ * var promise = User.mapReduce(o);
+ * promise.then(function (model, stats) {
+ * console.log('map reduce took %d ms', stats.processtime)
+ * return model.find().where('value').gt(10).exec();
+ * }).then(function (docs) {
+ * console.log(docs);
+ * }).then(null, handleError).end()
+ *
+ * @param {Object} o an object specifying map-reduce options
+ * @param {Function} [callback] optional callback
+ * @see http://www.mongodb.org/display/DOCS/MapReduce
+ * @return {Promise}
+ * @api public
+ */
+
+Model.mapReduce = function mapReduce(o, callback) {
+ var _this = this;
+ if (callback) {
+ callback = this.$wrapCallback(callback);
+ }
+ var Promise = PromiseProvider.get();
+ return new Promise.ES6(function(resolve, reject) {
+ if (!Model.mapReduce.schema) {
+ var opts = {noId: true, noVirtualId: true, strict: false};
+ Model.mapReduce.schema = new Schema({}, opts);
+ }
+
+ if (!o.out) o.out = {inline: 1};
+ if (o.verbose !== false) o.verbose = true;
+
+ o.map = String(o.map);
+ o.reduce = String(o.reduce);
+
+ if (o.query) {
+ var q = new _this.Query(o.query);
+ q.cast(_this);
+ o.query = q._conditions;
+ q = undefined;
+ }
+
+ _this.collection.mapReduce(null, null, o, function(err, ret, stats) {
+ if (err) {
+ callback && callback(err);
+ reject(err);
+ return;
+ }
+
+ if (ret.findOne && ret.mapReduce) {
+ // returned a collection, convert to Model
+ var model = Model.compile(
+ '_mapreduce_' + ret.collectionName
+ , Model.mapReduce.schema
+ , ret.collectionName
+ , _this.db
+ , _this.base);
+
+ model._mapreduce = true;
+
+ callback && callback(null, model, stats);
+ return resolve(model, stats);
+ }
+
+ callback && callback(null, ret, stats);
+ resolve(ret, stats);
+ });
+ });
+};
+
+/**
+ * geoNear support for Mongoose
+ *
+ * ####Options:
+ * - `lean` {Boolean} return the raw object
+ * - All options supported by the driver are also supported
+ *
+ * ####Example:
+ *
+ * // Legacy point
+ * Model.geoNear([1,3], { maxDistance : 5, spherical : true }, function(err, results, stats) {
+ * console.log(results);
+ * });
+ *
+ * // geoJson
+ * var point = { type : "Point", coordinates : [9,9] };
+ * Model.geoNear(point, { maxDistance : 5, spherical : true }, function(err, results, stats) {
+ * console.log(results);
+ * });
+ *
+ * @param {Object|Array} GeoJSON point or legacy coordinate pair [x,y] to search near
+ * @param {Object} options for the qurery
+ * @param {Function} [callback] optional callback for the query
+ * @return {Promise}
+ * @see http://docs.mongodb.org/manual/core/2dsphere/
+ * @see http://mongodb.github.io/node-mongodb-native/api-generated/collection.html?highlight=geonear#geoNear
+ * @api public
+ */
+
+Model.geoNear = function(near, options, callback) {
+ if (typeof options === 'function') {
+ callback = options;
+ options = {};
+ }
+
+ if (callback) {
+ callback = this.$wrapCallback(callback);
+ }
+
+ var _this = this;
+ var Promise = PromiseProvider.get();
+ if (!near) {
+ return new Promise.ES6(function(resolve, reject) {
+ var error = new Error('Must pass a near option to geoNear');
+ reject(error);
+ callback && callback(error);
+ });
+ }
+
+ var x, y;
+
+ return new Promise.ES6(function(resolve, reject) {
+ var handler = function(err, res) {
+ if (err) {
+ reject(err);
+ callback && callback(err);
+ return;
+ }
+ if (options.lean) {
+ resolve(res.results, res.stats);
+ callback && callback(null, res.results, res.stats);
+ return;
+ }
+
+ var count = res.results.length;
+ // if there are no results, fulfill the promise now
+ if (count === 0) {
+ resolve(res.results, res.stats);
+ callback && callback(null, res.results, res.stats);
+ return;
+ }
+
+ var errSeen = false;
+
+ function init(err) {
+ if (err && !errSeen) {
+ errSeen = true;
+ reject(err);
+ callback && callback(err);
+ return;
+ }
+ if (--count <= 0) {
+ resolve(res.results, res.stats);
+ callback && callback(null, res.results, res.stats);
+ }
+ }
+
+ for (var i = 0; i < res.results.length; i++) {
+ var temp = res.results[i].obj;
+ res.results[i].obj = new _this();
+ res.results[i].obj.init(temp, init);
+ }
+ };
+
+ if (Array.isArray(near)) {
+ if (near.length !== 2) {
+ var error = new Error('If using legacy coordinates, must be an array ' +
+ 'of size 2 for geoNear');
+ reject(error);
+ callback && callback(error);
+ return;
+ }
+ x = near[0];
+ y = near[1];
+ _this.collection.geoNear(x, y, options, handler);
+ } else {
+ if (near.type !== 'Point' || !Array.isArray(near.coordinates)) {
+ error = new Error('Must pass either a legacy coordinate array or ' +
+ 'GeoJSON Point to geoNear');
+ reject(error);
+ callback && callback(error);
+ return;
+ }
+
+ _this.collection.geoNear(near, options, handler);
+ }
+ });
+};
+
+/**
+ * Performs [aggregations](http://docs.mongodb.org/manual/applications/aggregation/) on the models collection.
+ *
+ * If a `callback` is passed, the `aggregate` is executed and a `Promise` is returned. If a callback is not passed, the `aggregate` itself is returned.
+ *
+ * ####Example:
+ *
+ * // Find the max balance of all accounts
+ * Users.aggregate(
+ * { $group: { _id: null, maxBalance: { $max: '$balance' }}}
+ * , { $project: { _id: 0, maxBalance: 1 }}
+ * , function (err, res) {
+ * if (err) return handleError(err);
+ * console.log(res); // [ { maxBalance: 98000 } ]
+ * });
+ *
+ * // Or use the aggregation pipeline builder.
+ * Users.aggregate()
+ * .group({ _id: null, maxBalance: { $max: '$balance' } })
+ * .select('-id maxBalance')
+ * .exec(function (err, res) {
+ * if (err) return handleError(err);
+ * console.log(res); // [ { maxBalance: 98 } ]
+ * });
+ *
+ * ####NOTE:
+ *
+ * - Arguments are not cast to the model's schema because `$project` operators allow redefining the "shape" of the documents at any stage of the pipeline, which may leave documents in an incompatible format.
+ * - The documents returned are plain javascript objects, not mongoose documents (since any shape of document can be returned).
+ * - Requires MongoDB >= 2.1
+ *
+ * @see Aggregate #aggregate_Aggregate
+ * @see MongoDB http://docs.mongodb.org/manual/applications/aggregation/
+ * @param {Object|Array} [...] aggregation pipeline operator(s) or operator array
+ * @param {Function} [callback]
+ * @return {Aggregate|Promise}
+ * @api public
+ */
+
+Model.aggregate = function aggregate() {
+ var args = [].slice.call(arguments),
+ aggregate,
+ callback;
+
+ if (typeof args[args.length - 1] === 'function') {
+ callback = args.pop();
+ }
+
+ if (args.length === 1 && util.isArray(args[0])) {
+ aggregate = new Aggregate(args[0]);
+ } else {
+ aggregate = new Aggregate(args);
+ }
+
+ aggregate.model(this);
+
+ if (typeof callback === 'undefined') {
+ return aggregate;
+ }
+
+ if (callback) {
+ callback = this.$wrapCallback(callback);
+ }
+
+ aggregate.exec(callback);
+};
+
+/**
+ * Implements `$geoSearch` functionality for Mongoose
+ *
+ * ####Example:
+ *
+ * var options = { near: [10, 10], maxDistance: 5 };
+ * Locations.geoSearch({ type : "house" }, options, function(err, res) {
+ * console.log(res);
+ * });
+ *
+ * ####Options:
+ * - `near` {Array} x,y point to search for
+ * - `maxDistance` {Number} the maximum distance from the point near that a result can be
+ * - `limit` {Number} The maximum number of results to return
+ * - `lean` {Boolean} return the raw object instead of the Mongoose Model
+ *
+ * @param {Object} conditions an object that specifies the match condition (required)
+ * @param {Object} options for the geoSearch, some (near, maxDistance) are required
+ * @param {Function} [callback] optional callback
+ * @return {Promise}
+ * @see http://docs.mongodb.org/manual/reference/command/geoSearch/
+ * @see http://docs.mongodb.org/manual/core/geohaystack/
+ * @api public
+ */
+
+Model.geoSearch = function(conditions, options, callback) {
+ if (typeof options === 'function') {
+ callback = options;
+ options = {};
+ }
+ if (callback) {
+ callback = this.$wrapCallback(callback);
+ }
+
+ var _this = this;
+ var Promise = PromiseProvider.get();
+ return new Promise.ES6(function(resolve, reject) {
+ var error;
+ if (conditions === undefined || !utils.isObject(conditions)) {
+ error = new Error('Must pass conditions to geoSearch');
+ } else if (!options.near) {
+ error = new Error('Must specify the near option in geoSearch');
+ } else if (!Array.isArray(options.near)) {
+ error = new Error('near option must be an array [x, y]');
+ }
+
+ if (error) {
+ callback && callback(error);
+ reject(error);
+ return;
+ }
+
+ // send the conditions in the options object
+ options.search = conditions;
+
+ _this.collection.geoHaystackSearch(options.near[0], options.near[1], options, function(err, res) {
+ // have to deal with driver problem. Should be fixed in a soon-ish release
+ // (7/8/2013)
+ if (err) {
+ callback && callback(err);
+ reject(err);
+ return;
+ }
+
+ var count = res.results.length;
+ if (options.lean || count === 0) {
+ callback && callback(null, res.results, res.stats);
+ resolve(res.results, res.stats);
+ return;
+ }
+
+ var errSeen = false;
+
+ function init(err) {
+ if (err && !errSeen) {
+ callback && callback(err);
+ reject(err);
+ return;
+ }
+
+ if (!--count && !errSeen) {
+ callback && callback(null, res.results, res.stats);
+ resolve(res.results, res.stats);
+ }
+ }
+
+ for (var i = 0; i < res.results.length; i++) {
+ var temp = res.results[i];
+ res.results[i] = new _this();
+ res.results[i].init(temp, {}, init);
+ }
+ });
+ });
+};
+
+/**
+ * Populates document references.
+ *
+ * ####Available options:
+ *
+ * - path: space delimited path(s) to populate
+ * - select: optional fields to select
+ * - match: optional query conditions to match
+ * - model: optional name of the model to use for population
+ * - options: optional query options like sort, limit, etc
+ *
+ * ####Examples:
+ *
+ * // populates a single object
+ * User.findById(id, function (err, user) {
+ * var opts = [
+ * { path: 'company', match: { x: 1 }, select: 'name' }
+ * , { path: 'notes', options: { limit: 10 }, model: 'override' }
+ * ]
+ *
+ * User.populate(user, opts, function (err, user) {
+ * console.log(user);
+ * })
+ * })
+ *
+ * // populates an array of objects
+ * User.find(match, function (err, users) {
+ * var opts = [{ path: 'company', match: { x: 1 }, select: 'name' }]
+ *
+ * var promise = User.populate(users, opts);
+ * promise.then(console.log).end();
+ * })
+ *
+ * // imagine a Weapon model exists with two saved documents:
+ * // { _id: 389, name: 'whip' }
+ * // { _id: 8921, name: 'boomerang' }
+ *
+ * var user = { name: 'Indiana Jones', weapon: 389 }
+ * Weapon.populate(user, { path: 'weapon', model: 'Weapon' }, function (err, user) {
+ * console.log(user.weapon.name) // whip
+ * })
+ *
+ * // populate many plain objects
+ * var users = [{ name: 'Indiana Jones', weapon: 389 }]
+ * users.push({ name: 'Batman', weapon: 8921 })
+ * Weapon.populate(users, { path: 'weapon' }, function (err, users) {
+ * users.forEach(function (user) {
+ * console.log('%s uses a %s', users.name, user.weapon.name)
+ * // Indiana Jones uses a whip
+ * // Batman uses a boomerang
+ * })
+ * })
+ * // Note that we didn't need to specify the Weapon model because
+ * // we were already using it's populate() method.
+ *
+ * @param {Document|Array} docs Either a single document or array of documents to populate.
+ * @param {Object} options A hash of key/val (path, options) used for population.
+ * @param {Function} [callback(err,doc)] Optional callback, executed upon completion. Receives `err` and the `doc(s)`.
+ * @return {Promise}
+ * @api public
+ */
+
+Model.populate = function(docs, paths, callback) {
+ var _this = this;
+ if (callback) {
+ callback = this.$wrapCallback(callback);
+ }
+
+ // normalized paths
+ var noPromise = paths && !!paths.__noPromise;
+ paths = utils.populate(paths);
+
+ // data that should persist across subPopulate calls
+ var cache = {};
+
+ if (noPromise) {
+ _populate(this, docs, paths, cache, callback);
+ } else {
+ var Promise = PromiseProvider.get();
+ return new Promise.ES6(function(resolve, reject) {
+ _populate(_this, docs, paths, cache, function(error, docs) {
+ if (error) {
+ callback && callback(error);
+ reject(error);
+ } else {
+ callback && callback(null, docs);
+ resolve(docs);
+ }
+ });
+ });
+ }
+};
+
+/*!
+ * Populate helper
+ *
+ * @param {Model} model the model to use
+ * @param {Document|Array} docs Either a single document or array of documents to populate.
+ * @param {Object} paths
+ * @param {Function} [cb(err,doc)] Optional callback, executed upon completion. Receives `err` and the `doc(s)`.
+ * @return {Function}
+ * @api private
+ */
+
+function _populate(model, docs, paths, cache, callback) {
+ var pending = paths.length;
+
+ if (pending === 0) {
+ return callback(null, docs);
+ }
+
+ // each path has its own query options and must be executed separately
+ var i = pending;
+ var path;
+ while (i--) {
+ path = paths[i];
+ populate(model, docs, path, next);
+ }
+
+ function next(err) {
+ if (err) {
+ return callback(err);
+ }
+ if (--pending) {
+ return;
+ }
+ callback(null, docs);
+ }
+}
+
+/*!
+ * Populates `docs`
+ */
+var excludeIdReg = /\s?-_id\s?/,
+ excludeIdRegGlobal = /\s?-_id\s?/g;
+
+function populate(model, docs, options, callback) {
+ var modelsMap;
+
+ // normalize single / multiple docs passed
+ if (!Array.isArray(docs)) {
+ docs = [docs];
+ }
+
+ if (docs.length === 0 || docs.every(utils.isNullOrUndefined)) {
+ return callback();
+ }
+
+ modelsMap = getModelsMapForPopulate(model, docs, options);
+
+ var i, len = modelsMap.length,
+ mod, match, select, vals = [];
+
+ function flatten(item) {
+ // no need to include undefined values in our query
+ return undefined !== item;
+ }
+
+ var _remaining = len;
+ var hasOne = false;
+ for (i = 0; i < len; i++) {
+ mod = modelsMap[i];
+ select = mod.options.select;
+
+ if (mod.options.match) {
+ match = utils.object.shallowCopy(mod.options.match);
+ } else {
+ match = {};
+ }
+
+ var ids = utils.array.flatten(mod.ids, flatten);
+ ids = utils.array.unique(ids);
+
+ if (ids.length === 0 || ids.every(utils.isNullOrUndefined)) {
+ --_remaining;
+ continue;
+ }
+
+ hasOne = true;
+ if (mod.foreignField !== '_id' || !match['_id']) {
+ match[mod.foreignField] = { $in: ids };
+ }
+
+ var assignmentOpts = {};
+ assignmentOpts.sort = mod.options.options && mod.options.options.sort || undefined;
+ assignmentOpts.excludeId = excludeIdReg.test(select) || (select && select._id === 0);
+
+ if (assignmentOpts.excludeId) {
+ // override the exclusion from the query so we can use the _id
+ // for document matching during assignment. we'll delete the
+ // _id back off before returning the result.
+ if (typeof select === 'string') {
+ select = select.replace(excludeIdRegGlobal, ' ');
+ } else {
+ // preserve original select conditions by copying
+ select = utils.object.shallowCopy(select);
+ delete select._id;
+ }
+ }
+
+ if (mod.options.options && mod.options.options.limit) {
+ assignmentOpts.originalLimit = mod.options.options.limit;
+ mod.options.options.limit = mod.options.options.limit * ids.length;
+ }
+
+ var subPopulate = mod.options.populate;
+ var query = mod.Model.find(match, select, mod.options.options);
+ if (subPopulate) {
+ query.populate(subPopulate);
+ }
+ query.exec(next.bind(this, mod, assignmentOpts));
+ }
+
+ if (!hasOne) {
+ return callback();
+ }
+
+ function next(options, assignmentOpts, err, valsFromDb) {
+ if (err) return callback(err);
+ vals = vals.concat(valsFromDb);
+ _assign(null, vals, options, assignmentOpts);
+ if (--_remaining === 0) {
+ callback();
+ }
+ }
+
+ function _assign(err, vals, mod, assignmentOpts) {
+ if (err) return callback(err);
+
+ var options = mod.options;
+ var _val;
+ var lean = options.options && options.options.lean,
+ len = vals.length,
+ rawOrder = {}, rawDocs = {}, key, val;
+
+ // optimization:
+ // record the document positions as returned by
+ // the query result.
+ for (var i = 0; i < len; i++) {
+ val = vals[i];
+ if (val) {
+ _val = utils.getValue(mod.foreignField, val);
+ if (Array.isArray(_val)) {
+ var _valLength = _val.length;
+ for (var j = 0; j < _valLength; ++j) {
+ if (_val[j] instanceof Document) {
+ _val[j] = _val[j]._id;
+ }
+ key = String(_val[j]);
+ if (rawDocs[key]) {
+ if (Array.isArray(rawDocs[key])) {
+ rawDocs[key].push(val);
+ rawOrder[key].push(i);
+ } else {
+ rawDocs[key] = [rawDocs[key], val];
+ rawOrder[key] = [rawOrder[key], i];
+ }
+ } else {
+ rawDocs[key] = val;
+ rawOrder[key] = i;
+ }
+ }
+ } else {
+ if (_val instanceof Document) {
+ _val = _val._id;
+ }
+ key = String(_val);
+ if (rawDocs[key]) {
+ if (Array.isArray(rawDocs[key])) {
+ rawDocs[key].push(val);
+ rawOrder[key].push(i);
+ } else {
+ rawDocs[key] = [rawDocs[key], val];
+ rawOrder[key] = [rawOrder[key], i];
+ }
+ } else {
+ rawDocs[key] = val;
+ rawOrder[key] = i;
+ }
+ }
+ // flag each as result of population
+ if (!lean) {
+ val.$__.wasPopulated = true;
+ }
+ }
+ }
+
+ assignVals({
+ originalModel: model,
+ rawIds: mod.ids,
+ localField: mod.localField,
+ foreignField: mod.foreignField,
+ rawDocs: rawDocs,
+ rawOrder: rawOrder,
+ docs: mod.docs,
+ path: options.path,
+ options: assignmentOpts,
+ justOne: mod.justOne,
+ isVirtual: mod.isVirtual
+ });
+ }
+}
+
+/*!
+ * Assigns documents returned from a population query back
+ * to the original document path.
+ */
+
+function assignVals(o) {
+ // replace the original ids in our intermediate _ids structure
+ // with the documents found by query
+ assignRawDocsToIdStructure(o.rawIds, o.rawDocs, o.rawOrder, o.options,
+ o.localField, o.foreignField);
+
+ // now update the original documents being populated using the
+ // result structure that contains real documents.
+
+ var docs = o.docs;
+ var rawIds = o.rawIds;
+ var options = o.options;
+
+ function setValue(val) {
+ return valueFilter(val, options);
+ }
+
+ for (var i = 0; i < docs.length; ++i) {
+ if (utils.getValue(o.path, docs[i]) == null &&
+ !o.originalModel.schema._getVirtual(o.path)) {
+ continue;
+ }
+
+ if (o.isVirtual && !o.justOne && !Array.isArray(rawIds[i])) {
+ rawIds[i] = [rawIds[i]];
+ }
+ utils.setValue(o.path, rawIds[i], docs[i], setValue);
+ }
+}
+
+/*!
+ * Assign `vals` returned by mongo query to the `rawIds`
+ * structure returned from utils.getVals() honoring
+ * query sort order if specified by user.
+ *
+ * This can be optimized.
+ *
+ * Rules:
+ *
+ * if the value of the path is not an array, use findOne rules, else find.
+ * for findOne the results are assigned directly to doc path (including null results).
+ * for find, if user specified sort order, results are assigned directly
+ * else documents are put back in original order of array if found in results
+ *
+ * @param {Array} rawIds
+ * @param {Array} vals
+ * @param {Boolean} sort
+ * @api private
+ */
+
+function assignRawDocsToIdStructure(rawIds, resultDocs, resultOrder, options, localFields, foreignFields, recursed) {
+ // honor user specified sort order
+ var newOrder = [];
+ var sorting = options.sort && rawIds.length > 1;
+ var doc;
+ var sid;
+ var id;
+
+ for (var i = 0; i < rawIds.length; ++i) {
+ id = rawIds[i];
+
+ if (Array.isArray(id)) {
+ // handle [ [id0, id2], [id3] ]
+ assignRawDocsToIdStructure(id, resultDocs, resultOrder, options, localFields, foreignFields, true);
+ newOrder.push(id);
+ continue;
+ }
+
+ if (id === null && !sorting) {
+ // keep nulls for findOne unless sorting, which always
+ // removes them (backward compat)
+ newOrder.push(id);
+ continue;
+ }
+
+ sid = String(id);
+
+ if (recursed) {
+ // apply find behavior
+
+ // assign matching documents in original order unless sorting
+ doc = resultDocs[sid];
+ if (doc) {
+ if (sorting) {
+ newOrder[resultOrder[sid]] = doc;
+ } else {
+ newOrder.push(doc);
+ }
+ } else {
+ newOrder.push(id);
+ }
+ } else {
+ // apply findOne behavior - if document in results, assign, else assign null
+ newOrder[i] = doc = resultDocs[sid] || null;
+ }
+ }
+
+ rawIds.length = 0;
+ if (newOrder.length) {
+ // reassign the documents based on corrected order
+
+ // forEach skips over sparse entries in arrays so we
+ // can safely use this to our advantage dealing with sorted
+ // result sets too.
+ newOrder.forEach(function(doc, i) {
+ if (!doc) {
+ return;
+ }
+ rawIds[i] = doc;
+ });
+ }
+}
+
+function getModelsMapForPopulate(model, docs, options) {
+ var i, doc, len = docs.length,
+ available = {},
+ map = [],
+ modelNameFromQuery = options.model && options.model.modelName || options.model,
+ schema, refPath, Model, currentOptions, modelNames, modelName, discriminatorKey, modelForFindSchema;
+
+ var originalOptions = utils.clone(options);
+ var isVirtual = false;
+
+ schema = model._getSchema(options.path);
+
+ if (schema && schema.caster) {
+ schema = schema.caster;
+ }
+
+ if (!schema && model.discriminators) {
+ discriminatorKey = model.schema.discriminatorMapping.key;
+ }
+
+ refPath = schema && schema.options && schema.options.refPath;
+
+ for (i = 0; i < len; i++) {
+ doc = docs[i];
+
+ if (refPath) {
+ modelNames = utils.getValue(refPath, doc);
+ if (Array.isArray(modelNames)) {
+ modelNames = modelNames.filter(function(v) {
+ return v != null;
+ });
+ }
+ } else {
+ if (!modelNameFromQuery) {
+ var modelForCurrentDoc = model;
+ var schemaForCurrentDoc;
+
+ if (!schema && discriminatorKey) {
+ modelForFindSchema = utils.getValue(discriminatorKey, doc);
+
+ if (modelForFindSchema) {
+ modelForCurrentDoc = model.db.model(modelForFindSchema);
+ schemaForCurrentDoc = modelForCurrentDoc._getSchema(options.path);
+
+ if (schemaForCurrentDoc && schemaForCurrentDoc.caster) {
+ schemaForCurrentDoc = schemaForCurrentDoc.caster;
+ }
+ }
+ } else {
+ schemaForCurrentDoc = schema;
+ }
+ var virtual = modelForCurrentDoc.schema._getVirtual(options.path);
+
+ if (schemaForCurrentDoc && schemaForCurrentDoc.options && schemaForCurrentDoc.options.ref) {
+ modelNames = [schemaForCurrentDoc.options.ref];
+ } else if (virtual && virtual.options && virtual.options.ref) {
+ modelNames = [virtual && virtual.options && virtual.options.ref];
+ isVirtual = true;
+ } else {
+ modelNames = [model.modelName];
+ }
+ } else {
+ modelNames = [modelNameFromQuery]; // query options
+ }
+ }
+
+ if (!modelNames) {
+ continue;
+ }
+
+ if (!Array.isArray(modelNames)) {
+ modelNames = [modelNames];
+ }
+
+ virtual = model.schema._getVirtual(options.path);
+ var localField = virtual && virtual.options ?
+ (virtual.$nestedSchemaPath ? virtual.$nestedSchemaPath + '.' : '') + virtual.options.localField :
+ options.path;
+ var foreignField = virtual && virtual.options ?
+ virtual.options.foreignField :
+ '_id';
+ var justOne = virtual && virtual.options && virtual.options.justOne;
+ if (virtual && virtual.options && virtual.options.ref) {
+ isVirtual = true;
+ }
+
+ if (virtual && (!localField || !foreignField)) {
+ throw new Error('If you are populating a virtual, you must set the ' +
+ 'localField and foreignField options');
+ }
+
+ options.isVirtual = isVirtual;
+ var ret = convertTo_id(utils.getValue(localField, doc));
+ var id = String(utils.getValue(foreignField, doc));
+ options._docs[id] = Array.isArray(ret) ? ret.slice() : ret;
+ if (doc.$__) {
+ doc.populated(options.path, options._docs[id], options);
+ }
+
+ var k = modelNames.length;
+ while (k--) {
+ modelName = modelNames[k];
+ Model = originalOptions.model && originalOptions.model.modelName ?
+ originalOptions.model :
+ model.db.model(modelName);
+
+ if (!available[modelName]) {
+ currentOptions = {
+ model: Model
+ };
+
+ if (isVirtual && virtual.options && virtual.options.options) {
+ currentOptions.options = utils.clone(virtual.options.options, {
+ retainKeyOrder: true
+ });
+ }
+ utils.merge(currentOptions, options);
+ if (schema && !discriminatorKey) {
+ currentOptions.model = Model;
+ }
+ options.model = Model;
+
+ available[modelName] = {
+ Model: Model,
+ options: currentOptions,
+ docs: [doc],
+ ids: [ret],
+ // Assume only 1 localField + foreignField
+ localField: localField,
+ foreignField: foreignField,
+ justOne: justOne,
+ isVirtual: isVirtual
+ };
+ map.push(available[modelName]);
+ } else {
+ available[modelName].docs.push(doc);
+ available[modelName].ids.push(ret);
+ }
+ }
+ }
+
+ return map;
+}
+
+/*!
+ * Retrieve the _id of `val` if a Document or Array of Documents.
+ *
+ * @param {Array|Document|Any} val
+ * @return {Array|Document|Any}
+ */
+
+function convertTo_id(val) {
+ if (val instanceof Model) return val._id;
+
+ if (Array.isArray(val)) {
+ for (var i = 0; i < val.length; ++i) {
+ if (val[i] instanceof Model) {
+ val[i] = val[i]._id;
+ }
+ }
+ if (val.isMongooseArray) {
+ return new MongooseArray(val, val._path, val._parent);
+ }
+
+ return [].concat(val);
+ }
+
+ return val;
+}
+
+/*!
+ * 1) Apply backwards compatible find/findOne behavior to sub documents
+ *
+ * find logic:
+ * a) filter out non-documents
+ * b) remove _id from sub docs when user specified
+ *
+ * findOne
+ * a) if no doc found, set to null
+ * b) remove _id from sub docs when user specified
+ *
+ * 2) Remove _ids when specified by users query.
+ *
+ * background:
+ * _ids are left in the query even when user excludes them so
+ * that population mapping can occur.
+ */
+
+function valueFilter(val, assignmentOpts) {
+ if (Array.isArray(val)) {
+ // find logic
+ var ret = [];
+ var numValues = val.length;
+ for (var i = 0; i < numValues; ++i) {
+ var subdoc = val[i];
+ if (!isDoc(subdoc)) continue;
+ maybeRemoveId(subdoc, assignmentOpts);
+ ret.push(subdoc);
+ if (assignmentOpts.originalLimit &&
+ ret.length >= assignmentOpts.originalLimit) {
+ break;
+ }
+ }
+
+ // Since we don't want to have to create a new mongoosearray, make sure to
+ // modify the array in place
+ while (val.length > ret.length) {
+ Array.prototype.pop.apply(val, []);
+ }
+ for (i = 0; i < ret.length; ++i) {
+ val[i] = ret[i];
+ }
+ return val;
+ }
+
+ // findOne
+ if (isDoc(val)) {
+ maybeRemoveId(val, assignmentOpts);
+ return val;
+ }
+
+ return null;
+}
+
+/*!
+ * Remove _id from `subdoc` if user specified "lean" query option
+ */
+
+function maybeRemoveId(subdoc, assignmentOpts) {
+ if (assignmentOpts.excludeId) {
+ if (typeof subdoc.setValue === 'function') {
+ delete subdoc._doc._id;
+ } else {
+ delete subdoc._id;
+ }
+ }
+}
+
+/*!
+ * Determine if `doc` is a document returned
+ * by a populate query.
+ */
+
+function isDoc(doc) {
+ if (doc == null) {
+ return false;
+ }
+
+ var type = typeof doc;
+ if (type === 'string') {
+ return false;
+ }
+
+ if (type === 'number') {
+ return false;
+ }
+
+ if (Buffer.isBuffer(doc)) {
+ return false;
+ }
+
+ if (doc.constructor.name === 'ObjectID') {
+ return false;
+ }
+
+ // only docs
+ return true;
+}
+
+/**
+ * Finds the schema for `path`. This is different than
+ * calling `schema.path` as it also resolves paths with
+ * positional selectors (something.$.another.$.path).
+ *
+ * @param {String} path
+ * @return {Schema}
+ * @api private
+ */
+
+Model._getSchema = function _getSchema(path) {
+ return this.schema._getSchema(path);
+};
+
+/*!
+ * Compiler utility.
+ *
+ * @param {String|Function} name model name or class extending Model
+ * @param {Schema} schema
+ * @param {String} collectionName
+ * @param {Connection} connection
+ * @param {Mongoose} base mongoose instance
+ */
+
+Model.compile = function compile(name, schema, collectionName, connection, base) {
+ var versioningEnabled = schema.options.versionKey !== false;
+
+ if (versioningEnabled && !schema.paths[schema.options.versionKey]) {
+ // add versioning to top level documents only
+ var o = {};
+ o[schema.options.versionKey] = Number;
+ schema.add(o);
+ }
+
+ var model;
+ if (typeof name === 'function' && name.prototype instanceof Model) {
+ model = name;
+ name = model.name;
+ schema.loadClass(model, true);
+ } else {
+ // generate new class
+ model = function model(doc, fields, skipId) {
+ if (!(this instanceof model)) {
+ return new model(doc, fields, skipId);
+ }
+ Model.call(this, doc, fields, skipId);
+ };
+ }
+
+ model.hooks = schema.s.hooks.clone();
+ model.base = base;
+ model.modelName = name;
+ if (!(model.prototype instanceof Model)) {
+ model.__proto__ = Model;
+ model.prototype.__proto__ = Model.prototype;
+ }
+ model.model = Model.prototype.model;
+ model.db = model.prototype.db = connection;
+ model.discriminators = model.prototype.discriminators = undefined;
+
+ model.prototype.$__setSchema(schema);
+
+ var collectionOptions = {
+ bufferCommands: schema.options.bufferCommands,
+ capped: schema.options.capped
+ };
+
+ model.prototype.collection = connection.collection(
+ collectionName
+ , collectionOptions
+ );
+
+ // apply methods and statics
+ applyMethods(model, schema);
+ applyStatics(model, schema);
+
+ model.schema = model.prototype.schema;
+ model.collection = model.prototype.collection;
+
+ // Create custom query constructor
+ model.Query = function() {
+ Query.apply(this, arguments);
+ this.options.retainKeyOrder = model.schema.options.retainKeyOrder;
+ };
+ model.Query.prototype = Object.create(Query.prototype);
+ model.Query.base = Query.base;
+ applyQueryMethods(model, schema.query);
+
+ var kareemOptions = { useErrorHandlers: true };
+ model.$__insertMany = model.hooks.createWrapper('insertMany',
+ model.insertMany, model, kareemOptions);
+ model.insertMany = function(arr, callback) {
+ var Promise = PromiseProvider.get();
+ return new Promise.ES6(function(resolve, reject) {
+ model.$__insertMany(arr, function(error, result) {
+ if (error) {
+ callback && callback(error);
+ return reject(error);
+ }
+ callback && callback(null, result);
+ resolve(result);
+ });
+ });
+ };
+
+ return model;
+};
+
+/*!
+ * Register methods for this model
+ *
+ * @param {Model} model
+ * @param {Schema} schema
+ */
+var applyMethods = function(model, schema) {
+ function apply(method, schema) {
+ Object.defineProperty(model.prototype, method, {
+ get: function() {
+ var h = {};
+ for (var k in schema.methods[method]) {
+ h[k] = schema.methods[method][k].bind(this);
+ }
+ return h;
+ },
+ configurable: true
+ });
+ }
+ for (var method in schema.methods) {
+ if (schema.tree.hasOwnProperty(method)) {
+ throw new Error('You have a method and a property in your schema both ' +
+ 'named "' + method + '"');
+ }
+ if (typeof schema.methods[method] === 'function') {
+ model.prototype[method] = schema.methods[method];
+ } else {
+ apply(method, schema);
+ }
+ }
+};
+
+/*!
+ * Register statics for this model
+ * @param {Model} model
+ * @param {Schema} schema
+ */
+var applyStatics = function(model, schema) {
+ for (var i in schema.statics) {
+ model[i] = schema.statics[i];
+ }
+};
+
+/*!
+ * Register custom query methods for this model
+ *
+ * @param {Model} model
+ * @param {Schema} schema
+ */
+
+function applyQueryMethods(model, methods) {
+ for (var i in methods) {
+ model.Query.prototype[i] = methods[i];
+ }
+}
+
+/*!
+ * Subclass this model with `conn`, `schema`, and `collection` settings.
+ *
+ * @param {Connection} conn
+ * @param {Schema} [schema]
+ * @param {String} [collection]
+ * @return {Model}
+ */
+
+Model.__subclass = function subclass(conn, schema, collection) {
+ // subclass model using this connection and collection name
+ var _this = this;
+
+ var Model = function Model(doc, fields, skipId) {
+ if (!(this instanceof Model)) {
+ return new Model(doc, fields, skipId);
+ }
+ _this.call(this, doc, fields, skipId);
+ };
+
+ Model.__proto__ = _this;
+ Model.prototype.__proto__ = _this.prototype;
+ Model.db = Model.prototype.db = conn;
+
+ var s = schema && typeof schema !== 'string'
+ ? schema
+ : _this.prototype.schema;
+
+ var options = s.options || {};
+
+ if (!collection) {
+ collection = _this.prototype.schema.get('collection')
+ || utils.toCollectionName(_this.modelName, options);
+ }
+
+ var collectionOptions = {
+ bufferCommands: s ? options.bufferCommands : true,
+ capped: s && options.capped
+ };
+
+ Model.prototype.collection = conn.collection(collection, collectionOptions);
+ Model.collection = Model.prototype.collection;
+ Model.init();
+ return Model;
+};
+
+Model.$wrapCallback = function(callback) {
+ var _this = this;
+ return function() {
+ try {
+ callback.apply(null, arguments);
+ } catch (error) {
+ _this.emit('error', error);
+ }
+ };
+};
+
+/*!
+ * Module exports.
+ */
+
+module.exports = exports = Model;
diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/promise.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/promise.js
new file mode 100644
index 0000000..72163ea
--- /dev/null
+++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/promise.js
@@ -0,0 +1,314 @@
+/*!
+ * 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();
+ *
+ * DEPRECATED. Mongoose 5.0 will use native promises by default (or bluebird,
+ * if native promises are not present) but still
+ * support plugging in your own ES6-compatible promises library. Mongoose 5.0
+ * will **not** support mpromise.
+ *
+ * @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
+ * @deprecated
+ */
+
+function Promise(fn) {
+ MPromise.call(this, fn);
+}
+
+/**
+ * ES6-style promise constructor wrapper around mpromise.
+ *
+ * @param {Function} resolver
+ * @return {Promise} new promise
+ * @api public
+ */
+Promise.ES6 = function(resolver) {
+ var promise = new Promise();
+
+ // No try/catch for backwards compatibility
+ resolver(
+ function() {
+ promise.complete.apply(promise, arguments);
+ },
+ function(e) {
+ promise.error(e);
+ });
+
+ return promise;
+};
+
+/*!
+ * Inherit from mpromise
+ */
+
+Promise.prototype = Object.create(MPromise.prototype, {
+ constructor: {
+ value: Promise,
+ enumerable: false,
+ writable: true,
+ configurable: true
+ }
+});
+
+/*!
+ * ignore
+ */
+
+Promise.prototype.then = util.deprecate(Promise.prototype.then,
+ 'Mongoose: mpromise (mongoose\'s default promise library) is deprecated, ' +
+ 'plug in your own promise library instead: ' +
+ 'http://mongoosejs.com/docs/promises.html');
+
+/**
+ * ES6-style `.catch()` shorthand
+ *
+ * @method catch
+ * @memberOf Promise
+ * @param {Function} onReject
+ * @return {Promise}
+ * @api public
+ */
+
+Promise.prototype.catch = function(onReject) {
+ return this.then(null, onReject);
+};
+
+/*!
+ * 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
+ * @deprecated
+ */
+
+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
+ * @deprecated
+ */
+
+/**
+ * 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
+ * @deprecated
+ */
+
+/**
+ * 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
+ * @deprecated
+ */
+
+/*!
+ * expose
+ */
+
+module.exports = Promise;
diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/promise_provider.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/promise_provider.js
new file mode 100644
index 0000000..368cf85
--- /dev/null
+++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/promise_provider.js
@@ -0,0 +1,51 @@
+/*!
+ * Module dependencies.
+ */
+
+var MPromise = require('./promise');
+
+/**
+ * Helper for multiplexing promise implementations
+ *
+ * @api private
+ */
+
+var Promise = {
+ _promise: MPromise
+};
+
+/**
+ * Get the current promise constructor
+ *
+ * @api private
+ */
+Promise.get = function() {
+ return Promise._promise;
+};
+
+/**
+ * Set the current promise constructor
+ *
+ * @api private
+ */
+
+Promise.set = function(lib) {
+ if (lib === MPromise) {
+ return Promise.reset();
+ }
+ Promise._promise = require('./ES6Promise');
+ Promise._promise.use(lib);
+ require('mquery').Promise = Promise._promise.ES6;
+};
+
+/**
+ * Resets to using mpromise
+ *
+ * @api private
+ */
+
+Promise.reset = function() {
+ Promise._promise = MPromise;
+};
+
+module.exports = Promise;
diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/query.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/query.js
new file mode 100644
index 0000000..66a5537
--- /dev/null
+++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/query.js
@@ -0,0 +1,3413 @@
+/*!
+ * Module dependencies.
+ */
+
+var PromiseProvider = require('./promise_provider');
+var QueryCursor = require('./querycursor');
+var QueryStream = require('./querystream');
+var StrictModeError = require('./error/strict');
+var cast = require('./cast');
+var helpers = require('./queryhelpers');
+var mquery = require('mquery');
+var readPref = require('./drivers').ReadPreference;
+var setDefaultsOnInsert = require('./services/setDefaultsOnInsert');
+var updateValidators = require('./services/updateValidators');
+var util = require('util');
+var utils = require('./utils');
+
+/**
+ * Query constructor used for building queries.
+ *
+ * ####Example:
+ *
+ * var query = new Query();
+ * query.setOptions({ lean : true });
+ * query.collection(model.collection);
+ * query.where('age').gte(21).exec(callback);
+ *
+ * @param {Object} [options]
+ * @param {Object} [model]
+ * @param {Object} [conditions]
+ * @param {Object} [collection] Mongoose collection
+ * @api private
+ */
+
+function Query(conditions, options, model, collection) {
+ // this stuff is for dealing with custom queries created by #toConstructor
+ if (!this._mongooseOptions) {
+ this._mongooseOptions = {};
+ }
+
+ // this is the case where we have a CustomQuery, we need to check if we got
+ // options passed in, and if we did, merge them in
+ if (options) {
+ var keys = Object.keys(options);
+ for (var i = 0; i < keys.length; ++i) {
+ var k = keys[i];
+ this._mongooseOptions[k] = options[k];
+ }
+ }
+
+ if (collection) {
+ this.mongooseCollection = collection;
+ }
+
+ if (model) {
+ this.model = model;
+ this.schema = model.schema;
+ }
+
+ // this is needed because map reduce returns a model that can be queried, but
+ // all of the queries on said model should be lean
+ if (this.model && this.model._mapreduce) {
+ this.lean();
+ }
+
+ // inherit mquery
+ mquery.call(this, this.mongooseCollection, options);
+
+ if (conditions) {
+ this.find(conditions);
+ }
+
+ if (this.schema) {
+ var kareemOptions = { useErrorHandlers: true };
+ this._count = this.model.hooks.createWrapper('count',
+ Query.prototype._count, this, kareemOptions);
+ this._execUpdate = this.model.hooks.createWrapper('update',
+ Query.prototype._execUpdate, this, kareemOptions);
+ this._find = this.model.hooks.createWrapper('find',
+ Query.prototype._find, this, kareemOptions);
+ this._findOne = this.model.hooks.createWrapper('findOne',
+ Query.prototype._findOne, this, kareemOptions);
+ this._findOneAndRemove = this.model.hooks.createWrapper('findOneAndRemove',
+ Query.prototype._findOneAndRemove, this, kareemOptions);
+ this._findOneAndUpdate = this.model.hooks.createWrapper('findOneAndUpdate',
+ Query.prototype._findOneAndUpdate, this, kareemOptions);
+ }
+}
+
+/*!
+ * inherit mquery
+ */
+
+Query.prototype = new mquery;
+Query.prototype.constructor = Query;
+Query.base = mquery.prototype;
+
+/**
+ * Flag to opt out of using `$geoWithin`.
+ *
+ * mongoose.Query.use$geoWithin = false;
+ *
+ * MongoDB 2.4 deprecated the use of `$within`, replacing it with `$geoWithin`. Mongoose uses `$geoWithin` by default (which is 100% backward compatible with $within). If you are running an older version of MongoDB, set this flag to `false` so your `within()` queries continue to work.
+ *
+ * @see http://docs.mongodb.org/manual/reference/operator/geoWithin/
+ * @default true
+ * @property use$geoWithin
+ * @memberOf Query
+ * @receiver Query
+ * @api public
+ */
+
+Query.use$geoWithin = mquery.use$geoWithin;
+
+/**
+ * Converts this query to a customized, reusable query constructor with all arguments and options retained.
+ *
+ * ####Example
+ *
+ * // Create a query for adventure movies and read from the primary
+ * // node in the replica-set unless it is down, in which case we'll
+ * // read from a secondary node.
+ * var query = Movie.find({ tags: 'adventure' }).read('primaryPreferred');
+ *
+ * // create a custom Query constructor based off these settings
+ * var Adventure = query.toConstructor();
+ *
+ * // Adventure is now a subclass of mongoose.Query and works the same way but with the
+ * // default query parameters and options set.
+ * Adventure().exec(callback)
+ *
+ * // further narrow down our query results while still using the previous settings
+ * Adventure().where({ name: /^Life/ }).exec(callback);
+ *
+ * // since Adventure is a stand-alone constructor we can also add our own
+ * // helper methods and getters without impacting global queries
+ * Adventure.prototype.startsWith = function (prefix) {
+ * this.where({ name: new RegExp('^' + prefix) })
+ * return this;
+ * }
+ * Object.defineProperty(Adventure.prototype, 'highlyRated', {
+ * get: function () {
+ * this.where({ rating: { $gt: 4.5 }});
+ * return this;
+ * }
+ * })
+ * Adventure().highlyRated.startsWith('Life').exec(callback)
+ *
+ * New in 3.7.3
+ *
+ * @return {Query} subclass-of-Query
+ * @api public
+ */
+
+Query.prototype.toConstructor = function toConstructor() {
+ var model = this.model;
+ var coll = this.mongooseCollection;
+
+ var CustomQuery = function(criteria, options) {
+ if (!(this instanceof CustomQuery)) {
+ return new CustomQuery(criteria, options);
+ }
+ this._mongooseOptions = utils.clone(p._mongooseOptions);
+ Query.call(this, criteria, options || null, model, coll);
+ };
+
+ util.inherits(CustomQuery, Query);
+
+ // set inherited defaults
+ var p = CustomQuery.prototype;
+
+ p.options = {};
+
+ p.setOptions(this.options);
+
+ p.op = this.op;
+ p._conditions = utils.clone(this._conditions, { retainKeyOrder: true });
+ p._fields = utils.clone(this._fields);
+ p._update = utils.clone(this._update);
+ p._path = this._path;
+ p._distinct = this._distinct;
+ p._collection = this._collection;
+ p._mongooseOptions = this._mongooseOptions;
+
+ return CustomQuery;
+};
+
+/**
+ * Specifies a javascript function or expression to pass to MongoDBs query system.
+ *
+ * ####Example
+ *
+ * query.$where('this.comments.length === 10 || this.name.length === 5')
+ *
+ * // or
+ *
+ * query.$where(function () {
+ * return this.comments.length === 10 || this.name.length === 5;
+ * })
+ *
+ * ####NOTE:
+ *
+ * Only use `$where` when you have a condition that cannot be met using other MongoDB operators like `$lt`.
+ * **Be sure to read about all of [its caveats](http://docs.mongodb.org/manual/reference/operator/where/) before using.**
+ *
+ * @see $where http://docs.mongodb.org/manual/reference/operator/where/
+ * @method $where
+ * @param {String|Function} js javascript string or function
+ * @return {Query} this
+ * @memberOf Query
+ * @method $where
+ * @api public
+ */
+
+/**
+ * Specifies a `path` for use with chaining.
+ *
+ * ####Example
+ *
+ * // instead of writing:
+ * User.find({age: {$gte: 21, $lte: 65}}, callback);
+ *
+ * // we can instead write:
+ * User.where('age').gte(21).lte(65);
+ *
+ * // passing query conditions is permitted
+ * User.find().where({ name: 'vonderful' })
+ *
+ * // chaining
+ * User
+ * .where('age').gte(21).lte(65)
+ * .where('name', /^vonderful/i)
+ * .where('friends').slice(10)
+ * .exec(callback)
+ *
+ * @method where
+ * @memberOf Query
+ * @param {String|Object} [path]
+ * @param {any} [val]
+ * @return {Query} this
+ * @api public
+ */
+
+/**
+ * Specifies the complementary comparison value for paths specified with `where()`
+ *
+ * ####Example
+ *
+ * User.where('age').equals(49);
+ *
+ * // is the same as
+ *
+ * User.where('age', 49);
+ *
+ * @method equals
+ * @memberOf Query
+ * @param {Object} val
+ * @return {Query} this
+ * @api public
+ */
+
+/**
+ * Specifies arguments for an `$or` condition.
+ *
+ * ####Example
+ *
+ * query.or([{ color: 'red' }, { status: 'emergency' }])
+ *
+ * @see $or http://docs.mongodb.org/manual/reference/operator/or/
+ * @method or
+ * @memberOf Query
+ * @param {Array} array array of conditions
+ * @return {Query} this
+ * @api public
+ */
+
+/**
+ * Specifies arguments for a `$nor` condition.
+ *
+ * ####Example
+ *
+ * query.nor([{ color: 'green' }, { status: 'ok' }])
+ *
+ * @see $nor http://docs.mongodb.org/manual/reference/operator/nor/
+ * @method nor
+ * @memberOf Query
+ * @param {Array} array array of conditions
+ * @return {Query} this
+ * @api public
+ */
+
+/**
+ * Specifies arguments for a `$and` condition.
+ *
+ * ####Example
+ *
+ * query.and([{ color: 'green' }, { status: 'ok' }])
+ *
+ * @method and
+ * @memberOf Query
+ * @see $and http://docs.mongodb.org/manual/reference/operator/and/
+ * @param {Array} array array of conditions
+ * @return {Query} this
+ * @api public
+ */
+
+/**
+ * Specifies a $gt query condition.
+ *
+ * When called with one argument, the most recent path passed to `where()` is used.
+ *
+ * ####Example
+ *
+ * Thing.find().where('age').gt(21)
+ *
+ * // or
+ * Thing.find().gt('age', 21)
+ *
+ * @method gt
+ * @memberOf Query
+ * @param {String} [path]
+ * @param {Number} val
+ * @see $gt http://docs.mongodb.org/manual/reference/operator/gt/
+ * @api public
+ */
+
+/**
+ * Specifies a $gte query condition.
+ *
+ * When called with one argument, the most recent path passed to `where()` is used.
+ *
+ * @method gte
+ * @memberOf Query
+ * @param {String} [path]
+ * @param {Number} val
+ * @see $gte http://docs.mongodb.org/manual/reference/operator/gte/
+ * @api public
+ */
+
+/**
+ * Specifies a $lt query condition.
+ *
+ * When called with one argument, the most recent path passed to `where()` is used.
+ *
+ * @method lt
+ * @memberOf Query
+ * @param {String} [path]
+ * @param {Number} val
+ * @see $lt http://docs.mongodb.org/manual/reference/operator/lt/
+ * @api public
+ */
+
+/**
+ * Specifies a $lte query condition.
+ *
+ * When called with one argument, the most recent path passed to `where()` is used.
+ *
+ * @method lte
+ * @see $lte http://docs.mongodb.org/manual/reference/operator/lte/
+ * @memberOf Query
+ * @param {String} [path]
+ * @param {Number} val
+ * @api public
+ */
+
+/**
+ * Specifies a $ne query condition.
+ *
+ * When called with one argument, the most recent path passed to `where()` is used.
+ *
+ * @see $ne http://docs.mongodb.org/manual/reference/operator/ne/
+ * @method ne
+ * @memberOf Query
+ * @param {String} [path]
+ * @param {Number} val
+ * @api public
+ */
+
+/**
+ * Specifies an $in query condition.
+ *
+ * When called with one argument, the most recent path passed to `where()` is used.
+ *
+ * @see $in http://docs.mongodb.org/manual/reference/operator/in/
+ * @method in
+ * @memberOf Query
+ * @param {String} [path]
+ * @param {Number} val
+ * @api public
+ */
+
+/**
+ * Specifies an $nin query condition.
+ *
+ * When called with one argument, the most recent path passed to `where()` is used.
+ *
+ * @see $nin http://docs.mongodb.org/manual/reference/operator/nin/
+ * @method nin
+ * @memberOf Query
+ * @param {String} [path]
+ * @param {Number} val
+ * @api public
+ */
+
+/**
+ * Specifies an $all query condition.
+ *
+ * When called with one argument, the most recent path passed to `where()` is used.
+ *
+ * @see $all http://docs.mongodb.org/manual/reference/operator/all/
+ * @method all
+ * @memberOf Query
+ * @param {String} [path]
+ * @param {Number} val
+ * @api public
+ */
+
+/**
+ * Specifies a $size query condition.
+ *
+ * When called with one argument, the most recent path passed to `where()` is used.
+ *
+ * ####Example
+ *
+ * MyModel.where('tags').size(0).exec(function (err, docs) {
+ * if (err) return handleError(err);
+ *
+ * assert(Array.isArray(docs));
+ * console.log('documents with 0 tags', docs);
+ * })
+ *
+ * @see $size http://docs.mongodb.org/manual/reference/operator/size/
+ * @method size
+ * @memberOf Query
+ * @param {String} [path]
+ * @param {Number} val
+ * @api public
+ */
+
+/**
+ * Specifies a $regex query condition.
+ *
+ * When called with one argument, the most recent path passed to `where()` is used.
+ *
+ * @see $regex http://docs.mongodb.org/manual/reference/operator/regex/
+ * @method regex
+ * @memberOf Query
+ * @param {String} [path]
+ * @param {Number} val
+ * @api public
+ */
+
+/**
+ * Specifies a $maxDistance query condition.
+ *
+ * When called with one argument, the most recent path passed to `where()` is used.
+ *
+ * @see $maxDistance http://docs.mongodb.org/manual/reference/operator/maxDistance/
+ * @method maxDistance
+ * @memberOf Query
+ * @param {String} [path]
+ * @param {Number} val
+ * @api public
+ */
+
+/**
+ * Specifies a `$mod` condition
+ *
+ * @method mod
+ * @memberOf Query
+ * @param {String} [path]
+ * @param {Number} val
+ * @return {Query} this
+ * @see $mod http://docs.mongodb.org/manual/reference/operator/mod/
+ * @api public
+ */
+
+/**
+ * Specifies an `$exists` condition
+ *
+ * ####Example
+ *
+ * // { name: { $exists: true }}
+ * Thing.where('name').exists()
+ * Thing.where('name').exists(true)
+ * Thing.find().exists('name')
+ *
+ * // { name: { $exists: false }}
+ * Thing.where('name').exists(false);
+ * Thing.find().exists('name', false);
+ *
+ * @method exists
+ * @memberOf Query
+ * @param {String} [path]
+ * @param {Number} val
+ * @return {Query} this
+ * @see $exists http://docs.mongodb.org/manual/reference/operator/exists/
+ * @api public
+ */
+
+/**
+ * Specifies an `$elemMatch` condition
+ *
+ * ####Example
+ *
+ * query.elemMatch('comment', { author: 'autobot', votes: {$gte: 5}})
+ *
+ * query.where('comment').elemMatch({ author: 'autobot', votes: {$gte: 5}})
+ *
+ * query.elemMatch('comment', function (elem) {
+ * elem.where('author').equals('autobot');
+ * elem.where('votes').gte(5);
+ * })
+ *
+ * query.where('comment').elemMatch(function (elem) {
+ * elem.where({ author: 'autobot' });
+ * elem.where('votes').gte(5);
+ * })
+ *
+ * @method elemMatch
+ * @memberOf Query
+ * @param {String|Object|Function} path
+ * @param {Object|Function} criteria
+ * @return {Query} this
+ * @see $elemMatch http://docs.mongodb.org/manual/reference/operator/elemMatch/
+ * @api public
+ */
+
+/**
+ * Defines a `$within` or `$geoWithin` argument for geo-spatial queries.
+ *
+ * ####Example
+ *
+ * query.where(path).within().box()
+ * query.where(path).within().circle()
+ * query.where(path).within().geometry()
+ *
+ * query.where('loc').within({ center: [50,50], radius: 10, unique: true, spherical: true });
+ * query.where('loc').within({ box: [[40.73, -73.9], [40.7, -73.988]] });
+ * query.where('loc').within({ polygon: [[],[],[],[]] });
+ *
+ * query.where('loc').within([], [], []) // polygon
+ * query.where('loc').within([], []) // box
+ * query.where('loc').within({ type: 'LineString', coordinates: [...] }); // geometry
+ *
+ * **MUST** be used after `where()`.
+ *
+ * ####NOTE:
+ *
+ * As of Mongoose 3.7, `$geoWithin` is always used for queries. To change this behavior, see [Query.use$geoWithin](#query_Query-use%2524geoWithin).
+ *
+ * ####NOTE:
+ *
+ * In Mongoose 3.7, `within` changed from a getter to a function. If you need the old syntax, use [this](https://github.com/ebensing/mongoose-within).
+ *
+ * @method within
+ * @see $polygon http://docs.mongodb.org/manual/reference/operator/polygon/
+ * @see $box http://docs.mongodb.org/manual/reference/operator/box/
+ * @see $geometry http://docs.mongodb.org/manual/reference/operator/geometry/
+ * @see $center http://docs.mongodb.org/manual/reference/operator/center/
+ * @see $centerSphere http://docs.mongodb.org/manual/reference/operator/centerSphere/
+ * @memberOf Query
+ * @return {Query} this
+ * @api public
+ */
+
+/**
+ * Specifies a $slice projection for an array.
+ *
+ * ####Example
+ *
+ * query.slice('comments', 5)
+ * query.slice('comments', -5)
+ * query.slice('comments', [10, 5])
+ * query.where('comments').slice(5)
+ * query.where('comments').slice([-10, 5])
+ *
+ * @method slice
+ * @memberOf Query
+ * @param {String} [path]
+ * @param {Number} val number/range of elements to slice
+ * @return {Query} this
+ * @see mongodb http://www.mongodb.org/display/DOCS/Retrieving+a+Subset+of+Fields#RetrievingaSubsetofFields-RetrievingaSubrangeofArrayElements
+ * @see $slice http://docs.mongodb.org/manual/reference/projection/slice/#prj._S_slice
+ * @api public
+ */
+
+/**
+ * Specifies the maximum number of documents the query will return.
+ *
+ * ####Example
+ *
+ * query.limit(20)
+ *
+ * ####Note
+ *
+ * Cannot be used with `distinct()`
+ *
+ * @method limit
+ * @memberOf Query
+ * @param {Number} val
+ * @api public
+ */
+
+/**
+ * Specifies the number of documents to skip.
+ *
+ * ####Example
+ *
+ * query.skip(100).limit(20)
+ *
+ * ####Note
+ *
+ * Cannot be used with `distinct()`
+ *
+ * @method skip
+ * @memberOf Query
+ * @param {Number} val
+ * @see cursor.skip http://docs.mongodb.org/manual/reference/method/cursor.skip/
+ * @api public
+ */
+
+/**
+ * Specifies the maxScan option.
+ *
+ * ####Example
+ *
+ * query.maxScan(100)
+ *
+ * ####Note
+ *
+ * Cannot be used with `distinct()`
+ *
+ * @method maxScan
+ * @memberOf Query
+ * @param {Number} val
+ * @see maxScan http://docs.mongodb.org/manual/reference/operator/maxScan/
+ * @api public
+ */
+
+/**
+ * Specifies the batchSize option.
+ *
+ * ####Example
+ *
+ * query.batchSize(100)
+ *
+ * ####Note
+ *
+ * Cannot be used with `distinct()`
+ *
+ * @method batchSize
+ * @memberOf Query
+ * @param {Number} val
+ * @see batchSize http://docs.mongodb.org/manual/reference/method/cursor.batchSize/
+ * @api public
+ */
+
+/**
+ * Specifies the `comment` option.
+ *
+ * ####Example
+ *
+ * query.comment('login query')
+ *
+ * ####Note
+ *
+ * Cannot be used with `distinct()`
+ *
+ * @method comment
+ * @memberOf Query
+ * @param {Number} val
+ * @see comment http://docs.mongodb.org/manual/reference/operator/comment/
+ * @api public
+ */
+
+/**
+ * Specifies this query as a `snapshot` query.
+ *
+ * ####Example
+ *
+ * query.snapshot() // true
+ * query.snapshot(true)
+ * query.snapshot(false)
+ *
+ * ####Note
+ *
+ * Cannot be used with `distinct()`
+ *
+ * @method snapshot
+ * @memberOf Query
+ * @see snapshot http://docs.mongodb.org/manual/reference/operator/snapshot/
+ * @return {Query} this
+ * @api public
+ */
+
+/**
+ * Sets query hints.
+ *
+ * ####Example
+ *
+ * query.hint({ indexA: 1, indexB: -1})
+ *
+ * ####Note
+ *
+ * Cannot be used with `distinct()`
+ *
+ * @method hint
+ * @memberOf Query
+ * @param {Object} val a hint object
+ * @return {Query} this
+ * @see $hint http://docs.mongodb.org/manual/reference/operator/hint/
+ * @api public
+ */
+
+/**
+ * Specifies which document fields to include or exclude (also known as the query "projection")
+ *
+ * When using string syntax, prefixing a path with `-` will flag that path as excluded. When a path does not have the `-` prefix, it is included. Lastly, if a path is prefixed with `+`, it forces inclusion of the path, which is useful for paths excluded at the [schema level](/docs/api.html#schematype_SchemaType-select).
+ *
+ * ####Example
+ *
+ * // include a and b, exclude other fields
+ * query.select('a b');
+ *
+ * // exclude c and d, include other fields
+ * query.select('-c -d');
+ *
+ * // or you may use object notation, useful when
+ * // you have keys already prefixed with a "-"
+ * query.select({ a: 1, b: 1 });
+ * query.select({ c: 0, d: 0 });
+ *
+ * // force inclusion of field excluded at schema level
+ * query.select('+path')
+ *
+ * ####NOTE:
+ *
+ * Cannot be used with `distinct()`.
+ *
+ * _v2 had slightly different syntax such as allowing arrays of field names. This support was removed in v3._
+ *
+ * @method select
+ * @memberOf Query
+ * @param {Object|String} arg
+ * @return {Query} this
+ * @see SchemaType
+ * @api public
+ */
+
+/**
+ * _DEPRECATED_ Sets the slaveOk option.
+ *
+ * **Deprecated** in MongoDB 2.2 in favor of [read preferences](#query_Query-read).
+ *
+ * ####Example:
+ *
+ * query.slaveOk() // true
+ * query.slaveOk(true)
+ * query.slaveOk(false)
+ *
+ * @method slaveOk
+ * @memberOf Query
+ * @deprecated use read() preferences instead if on mongodb >= 2.2
+ * @param {Boolean} v defaults to true
+ * @see mongodb http://docs.mongodb.org/manual/applications/replication/#read-preference
+ * @see slaveOk http://docs.mongodb.org/manual/reference/method/rs.slaveOk/
+ * @see read() #query_Query-read
+ * @return {Query} this
+ * @api public
+ */
+
+/**
+ * Determines the MongoDB nodes from which to read.
+ *
+ * ####Preferences:
+ *
+ * primary - (default) Read from primary only. Operations will produce an error if primary is unavailable. Cannot be combined with tags.
+ * secondary Read from secondary if available, otherwise error.
+ * primaryPreferred Read from primary if available, otherwise a secondary.
+ * secondaryPreferred Read from a secondary if available, otherwise read from the primary.
+ * nearest All operations read from among the nearest candidates, but unlike other modes, this option will include both the primary and all secondaries in the random selection.
+ *
+ * Aliases
+ *
+ * p primary
+ * pp primaryPreferred
+ * s secondary
+ * sp secondaryPreferred
+ * n nearest
+ *
+ * ####Example:
+ *
+ * new Query().read('primary')
+ * new Query().read('p') // same as primary
+ *
+ * new Query().read('primaryPreferred')
+ * new Query().read('pp') // same as primaryPreferred
+ *
+ * new Query().read('secondary')
+ * new Query().read('s') // same as secondary
+ *
+ * new Query().read('secondaryPreferred')
+ * new Query().read('sp') // same as secondaryPreferred
+ *
+ * new Query().read('nearest')
+ * new Query().read('n') // same as nearest
+ *
+ * // read from secondaries with matching tags
+ * new Query().read('s', [{ dc:'sf', s: 1 },{ dc:'ma', s: 2 }])
+ *
+ * Read more about how to use read preferrences [here](http://docs.mongodb.org/manual/applications/replication/#read-preference) and [here](http://mongodb.github.com/node-mongodb-native/driver-articles/anintroductionto1_1and2_2.html#read-preferences).
+ *
+ * @method read
+ * @memberOf Query
+ * @param {String} pref one of the listed preference options or 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
+ * @return {Query} this
+ * @api public
+ */
+
+Query.prototype.read = function read(pref, tags) {
+ // first cast into a ReadPreference object to support tags
+ var read = readPref.call(readPref, pref, tags);
+ return Query.base.read.call(this, read);
+};
+
+/**
+ * Merges another Query or conditions object into this one.
+ *
+ * When a Query is passed, conditions, field selection and options are merged.
+ *
+ * New in 3.7.0
+ *
+ * @method merge
+ * @memberOf Query
+ * @param {Query|Object} source
+ * @return {Query} this
+ */
+
+/**
+ * Sets query options.
+ *
+ * ####Options:
+ *
+ * - [tailable](http://www.mongodb.org/display/DOCS/Tailable+Cursors) *
+ * - [sort](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bsort(\)%7D%7D) *
+ * - [limit](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Blimit%28%29%7D%7D) *
+ * - [skip](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bskip%28%29%7D%7D) *
+ * - [maxscan](https://docs.mongodb.org/v3.2/reference/operator/meta/maxScan/#metaOp._S_maxScan) *
+ * - [batchSize](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7BbatchSize%28%29%7D%7D) *
+ * - [comment](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24comment) *
+ * - [snapshot](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bsnapshot%28%29%7D%7D) *
+ * - [hint](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24hint) *
+ * - [readPreference](http://docs.mongodb.org/manual/applications/replication/#read-preference) **
+ * - [lean](./api.html#query_Query-lean) *
+ * - [safe](http://www.mongodb.org/display/DOCS/getLastError+Command)
+ *
+ * _* denotes a query helper method is also available_
+ * _** query helper method to set `readPreference` is `read()`_
+ *
+ * @param {Object} options
+ * @api public
+ */
+
+Query.prototype.setOptions = function(options, overwrite) {
+ // overwrite is only for internal use
+ if (overwrite) {
+ // ensure that _mongooseOptions & options are two different objects
+ this._mongooseOptions = (options && utils.clone(options)) || {};
+ this.options = options || {};
+
+ if ('populate' in options) {
+ this.populate(this._mongooseOptions);
+ }
+ return this;
+ }
+
+ if (!(options && options.constructor.name === 'Object')) {
+ return this;
+ }
+
+ if (options && Array.isArray(options.populate)) {
+ var populate = options.populate;
+ delete options.populate;
+ var _numPopulate = populate.length;
+ for (var i = 0; i < _numPopulate; ++i) {
+ this.populate(populate[i]);
+ }
+ }
+
+ return Query.base.setOptions.call(this, options);
+};
+
+/**
+ * Returns the current query conditions as a JSON object.
+ *
+ * ####Example:
+ *
+ * var query = new Query();
+ * query.find({ a: 1 }).where('b').gt(2);
+ * query.getQuery(); // { a: 1, b: { $gt: 2 } }
+ *
+ * @return {Object} current query conditions
+ * @api public
+ */
+
+Query.prototype.getQuery = function() {
+ return this._conditions;
+};
+
+/**
+ * Returns the current update operations as a JSON object.
+ *
+ * ####Example:
+ *
+ * var query = new Query();
+ * query.update({}, { $set: { a: 5 } });
+ * query.getUpdate(); // { $set: { a: 5 } }
+ *
+ * @return {Object} current update operations
+ * @api public
+ */
+
+Query.prototype.getUpdate = function() {
+ return this._update;
+};
+
+/**
+ * Returns fields selection for this query.
+ *
+ * @method _fieldsForExec
+ * @return {Object}
+ * @api private
+ * @receiver Query
+ */
+
+/**
+ * Return an update document with corrected $set operations.
+ *
+ * @method _updateForExec
+ * @api private
+ * @receiver Query
+ */
+
+Query.prototype._updateForExec = function() {
+ var update = utils.clone(this._update, {
+ retainKeyOrder: true,
+ transform: false,
+ depopulate: true
+ });
+ var ops = Object.keys(update);
+ var i = ops.length;
+ var ret = {};
+
+ while (i--) {
+ var op = ops[i];
+
+ if (this.options.overwrite) {
+ ret[op] = update[op];
+ continue;
+ }
+
+ if ('$' !== op[0]) {
+ // fix up $set sugar
+ if (!ret.$set) {
+ if (update.$set) {
+ ret.$set = update.$set;
+ } else {
+ ret.$set = {};
+ }
+ }
+ ret.$set[op] = update[op];
+ ops.splice(i, 1);
+ if (!~ops.indexOf('$set')) ops.push('$set');
+ } else if ('$set' === op) {
+ if (!ret.$set) {
+ ret[op] = update[op];
+ }
+ } else {
+ ret[op] = update[op];
+ }
+ }
+
+ this._compiledUpdate = ret;
+ return ret;
+};
+
+/**
+ * Makes sure _path is set.
+ *
+ * @method _ensurePath
+ * @param {String} method
+ * @api private
+ * @receiver Query
+ */
+
+/**
+ * Determines if `conds` can be merged using `mquery().merge()`
+ *
+ * @method canMerge
+ * @memberOf Query
+ * @param {Object} conds
+ * @return {Boolean}
+ * @api private
+ */
+
+/**
+ * Returns default options for this query.
+ *
+ * @param {Model} model
+ * @api private
+ */
+
+Query.prototype._optionsForExec = function(model) {
+ var options = Query.base._optionsForExec.call(this);
+
+ delete options.populate;
+ delete options.retainKeyOrder;
+ model = model || this.model;
+
+ if (!model) {
+ return options;
+ }
+
+ if (!('safe' in options) && model.schema.options.safe) {
+ options.safe = model.schema.options.safe;
+ }
+
+ if (!('readPreference' in options) && model.schema.options.read) {
+ options.readPreference = model.schema.options.read;
+ }
+
+ return options;
+};
+
+/**
+ * Sets the lean option.
+ *
+ * Documents returned from queries with the `lean` option enabled are plain javascript objects, not [MongooseDocuments](#document-js). They have no `save` method, getters/setters or other Mongoose magic applied.
+ *
+ * ####Example:
+ *
+ * new Query().lean() // true
+ * new Query().lean(true)
+ * new Query().lean(false)
+ *
+ * Model.find().lean().exec(function (err, docs) {
+ * docs[0] instanceof mongoose.Document // false
+ * });
+ *
+ * This is a [great](https://groups.google.com/forum/#!topic/mongoose-orm/u2_DzDydcnA/discussion) option in high-performance read-only scenarios, especially when combined with [stream](#query_Query-stream).
+ *
+ * @param {Boolean} bool defaults to true
+ * @return {Query} this
+ * @api public
+ */
+
+Query.prototype.lean = function(v) {
+ this._mongooseOptions.lean = arguments.length ? !!v : true;
+ return this;
+};
+
+/**
+ * Thunk around find()
+ *
+ * @param {Function} [callback]
+ * @return {Query} this
+ * @api private
+ */
+Query.prototype._find = function(callback) {
+ if (this._castError) {
+ callback(this._castError);
+ return this;
+ }
+
+ this._applyPaths();
+ this._fields = this._castFields(this._fields);
+
+ var fields = this._fieldsForExec();
+ var options = this._mongooseOptions;
+ var _this = this;
+
+ var cb = function(err, docs) {
+ if (err) {
+ return callback(err);
+ }
+
+ if (docs.length === 0) {
+ return callback(null, docs);
+ }
+
+ if (!options.populate) {
+ return options.lean === true
+ ? callback(null, docs)
+ : completeMany(_this.model, docs, fields, _this, null, callback);
+ }
+
+ var pop = helpers.preparePopulationOptionsMQ(_this, options);
+ pop.__noPromise = true;
+ _this.model.populate(docs, pop, function(err, docs) {
+ if (err) return callback(err);
+ return options.lean === true
+ ? callback(null, docs)
+ : completeMany(_this.model, docs, fields, _this, pop, callback);
+ });
+ };
+
+ return Query.base.find.call(this, {}, cb);
+};
+
+/**
+ * Finds documents.
+ *
+ * When no `callback` is passed, the query is not executed. When the query is executed, the result will be an array of documents.
+ *
+ * ####Example
+ *
+ * query.find({ name: 'Los Pollos Hermanos' }).find(callback)
+ *
+ * @param {Object} [criteria] mongodb selector
+ * @param {Function} [callback]
+ * @return {Query} this
+ * @api public
+ */
+
+Query.prototype.find = function(conditions, callback) {
+ if (typeof conditions === 'function') {
+ callback = conditions;
+ conditions = {};
+ }
+
+ conditions = utils.toObject(conditions);
+
+ if (mquery.canMerge(conditions)) {
+ this.merge(conditions);
+ }
+
+ prepareDiscriminatorCriteria(this);
+
+ try {
+ this.cast(this.model);
+ this._castError = null;
+ } catch (err) {
+ this._castError = err;
+ }
+
+ // if we don't have a callback, then just return the query object
+ if (!callback) {
+ return Query.base.find.call(this);
+ }
+
+ this._find(callback);
+
+ return this;
+};
+
+/**
+ * Merges another Query or conditions object into this one.
+ *
+ * When a Query is passed, conditions, field selection and options are merged.
+ *
+ * @param {Query|Object} source
+ * @return {Query} this
+ */
+
+Query.prototype.merge = function(source) {
+ if (!source) {
+ return this;
+ }
+
+ var opts = { retainKeyOrder: this.options.retainKeyOrder, overwrite: true };
+
+ if (source instanceof Query) {
+ // if source has a feature, apply it to ourselves
+
+ if (source._conditions) {
+ utils.merge(this._conditions, source._conditions, opts);
+ }
+
+ if (source._fields) {
+ this._fields || (this._fields = {});
+ utils.merge(this._fields, source._fields, opts);
+ }
+
+ if (source.options) {
+ this.options || (this.options = {});
+ utils.merge(this.options, source.options, opts);
+ }
+
+ if (source._update) {
+ this._update || (this._update = {});
+ utils.mergeClone(this._update, source._update);
+ }
+
+ if (source._distinct) {
+ this._distinct = source._distinct;
+ }
+
+ return this;
+ }
+
+ // plain object
+ utils.merge(this._conditions, source, opts);
+
+ return this;
+};
+
+/*!
+ * hydrates many documents
+ *
+ * @param {Model} model
+ * @param {Array} docs
+ * @param {Object} fields
+ * @param {Query} self
+ * @param {Array} [pop] array of paths used in population
+ * @param {Function} callback
+ */
+
+function completeMany(model, docs, fields, self, pop, callback) {
+ var arr = [];
+ var count = docs.length;
+ var len = count;
+ var opts = pop ?
+ {populated: pop}
+ : undefined;
+ function init(err) {
+ if (err) return callback(err);
+ --count || callback(null, arr);
+ }
+ for (var i = 0; i < len; ++i) {
+ arr[i] = helpers.createModel(model, docs[i], fields);
+ arr[i].init(docs[i], opts, init);
+ }
+}
+
+/**
+ * Thunk around findOne()
+ *
+ * @param {Function} [callback]
+ * @see findOne http://docs.mongodb.org/manual/reference/method/db.collection.findOne/
+ * @api private
+ */
+
+Query.prototype._findOne = function(callback) {
+ if (this._castError) {
+ return callback(this._castError);
+ }
+
+ this._applyPaths();
+ this._fields = this._castFields(this._fields);
+
+ var options = this._mongooseOptions;
+ var projection = this._fieldsForExec();
+ var _this = this;
+
+ // don't pass in the conditions because we already merged them in
+ Query.base.findOne.call(_this, {}, function(err, doc) {
+ if (err) {
+ return callback(err);
+ }
+ if (!doc) {
+ return callback(null, null);
+ }
+
+ if (!options.populate) {
+ return options.lean === true
+ ? callback(null, doc)
+ : completeOne(_this.model, doc, null, projection, _this, null, callback);
+ }
+
+ var pop = helpers.preparePopulationOptionsMQ(_this, options);
+ pop.__noPromise = true;
+ _this.model.populate(doc, pop, function(err, doc) {
+ if (err) {
+ return callback(err);
+ }
+ return options.lean === true
+ ? callback(null, doc)
+ : completeOne(_this.model, doc, null, projection, _this, pop, callback);
+ });
+ });
+};
+
+/**
+ * Declares the query a findOne operation. When executed, the first found document is passed to the callback.
+ *
+ * Passing a `callback` executes the query. The result of the query is a single document.
+ *
+ * * *Note:* `conditions` is optional, and if `conditions` is null or undefined,
+ * mongoose will send an empty `findOne` command to MongoDB, which will return
+ * an arbitrary document. If you're querying by `_id`, use `Model.findById()`
+ * instead.
+ *
+ * ####Example
+ *
+ * var query = Kitten.where({ color: 'white' });
+ * query.findOne(function (err, kitten) {
+ * if (err) return handleError(err);
+ * if (kitten) {
+ * // doc may be null if no document matched
+ * }
+ * });
+ *
+ * @param {Object|Query} [criteria] mongodb selector
+ * @param {Object} [projection] optional fields to return
+ * @param {Function} [callback]
+ * @return {Query} this
+ * @see findOne http://docs.mongodb.org/manual/reference/method/db.collection.findOne/
+ * @see Query.select #query_Query-select
+ * @api public
+ */
+
+Query.prototype.findOne = function(conditions, projection, options, callback) {
+ if (typeof conditions === 'function') {
+ callback = conditions;
+ conditions = null;
+ projection = null;
+ options = null;
+ } else if (typeof projection === 'function') {
+ callback = projection;
+ options = null;
+ projection = null;
+ } else if (typeof options === 'function') {
+ callback = options;
+ options = null;
+ }
+
+ // make sure we don't send in the whole Document to merge()
+ conditions = utils.toObject(conditions);
+
+ this.op = 'findOne';
+
+ if (options) {
+ this.setOptions(options);
+ }
+
+ if (projection) {
+ this.select(projection);
+ }
+
+ if (mquery.canMerge(conditions)) {
+ this.merge(conditions);
+ } else if (conditions != null) {
+ throw new Error('Invalid argument to findOne(): ' +
+ util.inspect(conditions));
+ }
+
+ prepareDiscriminatorCriteria(this);
+
+ try {
+ this.cast(this.model);
+ this._castError = null;
+ } catch (err) {
+ this._castError = err;
+ }
+
+ if (!callback) {
+ // already merged in the conditions, don't need to send them in.
+ return Query.base.findOne.call(this);
+ }
+
+ this._findOne(callback);
+
+ return this;
+};
+
+/**
+ * Thunk around count()
+ *
+ * @param {Function} [callback]
+ * @see count http://docs.mongodb.org/manual/reference/method/db.collection.count/
+ * @api private
+ */
+
+Query.prototype._count = function(callback) {
+ try {
+ this.cast(this.model);
+ } catch (err) {
+ process.nextTick(function() {
+ callback(err);
+ });
+ return this;
+ }
+
+ var conds = this._conditions;
+ var options = this._optionsForExec();
+
+ this._collection.count(conds, options, utils.tick(callback));
+};
+
+/**
+ * Specifying this query as a `count` query.
+ *
+ * Passing a `callback` executes the query.
+ *
+ * ####Example:
+ *
+ * var countQuery = model.where({ 'color': 'black' }).count();
+ *
+ * query.count({ color: 'black' }).count(callback)
+ *
+ * query.count({ color: 'black' }, callback)
+ *
+ * query.where('color', 'black').count(function (err, count) {
+ * if (err) return handleError(err);
+ * console.log('there are %d kittens', count);
+ * })
+ *
+ * @param {Object} [criteria] mongodb selector
+ * @param {Function} [callback]
+ * @return {Query} this
+ * @see count http://docs.mongodb.org/manual/reference/method/db.collection.count/
+ * @api public
+ */
+
+Query.prototype.count = function(conditions, callback) {
+ if (typeof conditions === 'function') {
+ callback = conditions;
+ conditions = undefined;
+ }
+
+ if (mquery.canMerge(conditions)) {
+ this.merge(conditions);
+ }
+
+ this.op = 'count';
+ if (!callback) {
+ return this;
+ }
+
+ this._count(callback);
+
+ return this;
+};
+
+/**
+ * Declares or executes a distict() operation.
+ *
+ * Passing a `callback` executes the query.
+ *
+ * ####Example
+ *
+ * distinct(field, conditions, callback)
+ * distinct(field, conditions)
+ * distinct(field, callback)
+ * distinct(field)
+ * distinct(callback)
+ * distinct()
+ *
+ * @param {String} [field]
+ * @param {Object|Query} [criteria]
+ * @param {Function} [callback]
+ * @return {Query} this
+ * @see distinct http://docs.mongodb.org/manual/reference/method/db.collection.distinct/
+ * @api public
+ */
+
+Query.prototype.distinct = function(field, conditions, callback) {
+ if (!callback) {
+ if (typeof conditions === 'function') {
+ callback = conditions;
+ conditions = undefined;
+ } else if (typeof field === 'function') {
+ callback = field;
+ field = undefined;
+ conditions = undefined;
+ }
+ }
+
+ conditions = utils.toObject(conditions);
+
+ if (mquery.canMerge(conditions)) {
+ this.merge(conditions);
+ }
+
+ try {
+ this.cast(this.model);
+ } catch (err) {
+ if (!callback) {
+ throw err;
+ }
+ callback(err);
+ return this;
+ }
+
+ return Query.base.distinct.call(this, {}, field, callback);
+};
+
+/**
+ * Sets the sort order
+ *
+ * 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.
+ *
+ * ####Example
+ *
+ * // sort by "field" ascending and "test" descending
+ * query.sort({ field: 'asc', test: -1 });
+ *
+ * // equivalent
+ * query.sort('field -test');
+ *
+ * ####Note
+ *
+ * Cannot be used with `distinct()`
+ *
+ * @param {Object|String} arg
+ * @return {Query} this
+ * @see cursor.sort http://docs.mongodb.org/manual/reference/method/cursor.sort/
+ * @api public
+ */
+
+Query.prototype.sort = function(arg) {
+ var nArg = {};
+
+ if (arguments.length > 1) {
+ throw new Error('sort() only takes 1 Argument');
+ }
+
+ if (Array.isArray(arg)) {
+ // time to deal with the terrible syntax
+ for (var i = 0; i < arg.length; i++) {
+ if (!Array.isArray(arg[i])) throw new Error('Invalid sort() argument.');
+ nArg[arg[i][0]] = arg[i][1];
+ }
+ } else {
+ nArg = arg;
+ }
+
+ return Query.base.sort.call(this, nArg);
+};
+
+/**
+ * Declare and/or execute this query as a remove() operation.
+ *
+ * ####Example
+ *
+ * Model.remove({ artist: 'Anne Murray' }, callback)
+ *
+ * ####Note
+ *
+ * The operation is only executed when a callback is passed. To force execution without a callback, you must first call `remove()` and then execute it by using the `exec()` method.
+ *
+ * // not executed
+ * var query = Model.find().remove({ name: 'Anne Murray' })
+ *
+ * // executed
+ * query.remove({ name: 'Anne Murray' }, callback)
+ * query.remove({ name: 'Anne Murray' }).remove(callback)
+ *
+ * // executed without a callback
+ * query.exec()
+ *
+ * // summary
+ * query.remove(conds, fn); // executes
+ * query.remove(conds)
+ * query.remove(fn) // executes
+ * query.remove()
+ *
+ * @param {Object|Query} [criteria] mongodb selector
+ * @param {Function} [callback]
+ * @return {Query} this
+ * @see remove http://docs.mongodb.org/manual/reference/method/db.collection.remove/
+ * @api public
+ */
+
+Query.prototype.remove = function(cond, callback) {
+ if (typeof cond === 'function') {
+ callback = cond;
+ cond = null;
+ }
+
+ var cb = typeof callback === 'function';
+
+ try {
+ this.cast(this.model);
+ } catch (err) {
+ if (cb) return process.nextTick(callback.bind(null, err));
+ return this;
+ }
+
+ return Query.base.remove.call(this, cond, callback);
+};
+
+/*!
+ * hydrates a document
+ *
+ * @param {Model} model
+ * @param {Document} doc
+ * @param {Object} res 3rd parameter to callback
+ * @param {Object} fields
+ * @param {Query} self
+ * @param {Array} [pop] array of paths used in population
+ * @param {Function} callback
+ */
+
+function completeOne(model, doc, res, fields, self, pop, callback) {
+ var opts = pop ?
+ {populated: pop}
+ : undefined;
+
+ var casted = helpers.createModel(model, doc, fields);
+ casted.init(doc, opts, function(err) {
+ if (err) {
+ return callback(err);
+ }
+ if (res) {
+ return callback(null, casted, res);
+ }
+ callback(null, casted);
+ });
+}
+
+/*!
+ * If the model is a discriminator type and not root, then add the key & value to the criteria.
+ */
+
+function prepareDiscriminatorCriteria(query) {
+ if (!query || !query.model || !query.model.schema) {
+ return;
+ }
+
+ var schema = query.model.schema;
+
+ if (schema && schema.discriminatorMapping && !schema.discriminatorMapping.isRoot) {
+ query._conditions[schema.discriminatorMapping.key] = schema.discriminatorMapping.value;
+ }
+}
+
+/**
+ * Issues a mongodb [findAndModify](http://www.mongodb.org/display/DOCS/findAndModify+Command) update command.
+ *
+ * Finds a matching document, updates it according to the `update` arg, passing any `options`, and returns the found document (if any) to the callback. The query executes immediately if `callback` is passed.
+ *
+ * ####Available options
+ *
+ * - `new`: bool - if true, return the modified document rather than the original. defaults to false (changed in 4.0)
+ * - `upsert`: bool - creates the object if it doesn't exist. defaults to false.
+ * - `fields`: {Object|String} - Field selection. Equivalent to `.select(fields).findOneAndUpdate()`
+ * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update
+ * - `maxTimeMS`: puts a time limit on the query - requires mongodb >= 2.6.0
+ * - `runValidators`: if true, runs [update validators](/docs/validation.html#update-validators) on this command. Update validators validate the update operation against the model's schema.
+ * - `setDefaultsOnInsert`: if this and `upsert` are true, mongoose will apply the [defaults](http://mongoosejs.com/docs/defaults.html) specified in the model's schema if a new document is created. This option only works on MongoDB >= 2.4 because it relies on [MongoDB's `$setOnInsert` operator](https://docs.mongodb.org/v2.4/reference/operator/update/setOnInsert/).
+ * - `passRawResult`: if true, passes the [raw result from the MongoDB driver as the third callback parameter](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify)
+ * - `context` (string) if set to 'query' and `runValidators` is on, `this` will refer to the query in custom validator functions that update validation runs. Does nothing if `runValidators` is false.
+ *
+ * ####Callback Signature
+ * function(error, doc) {
+ * // error: any errors that occurred
+ * // doc: the document before updates are applied if `new: false`, or after updates if `new = true`
+ * }
+ *
+ * ####Examples
+ *
+ * query.findOneAndUpdate(conditions, update, options, callback) // executes
+ * query.findOneAndUpdate(conditions, update, options) // returns Query
+ * query.findOneAndUpdate(conditions, update, callback) // executes
+ * query.findOneAndUpdate(conditions, update) // returns Query
+ * query.findOneAndUpdate(update, callback) // returns Query
+ * query.findOneAndUpdate(update) // returns Query
+ * query.findOneAndUpdate(callback) // executes
+ * query.findOneAndUpdate() // returns Query
+ *
+ * @method findOneAndUpdate
+ * @memberOf Query
+ * @param {Object|Query} [query]
+ * @param {Object} [doc]
+ * @param {Object} [options]
+ * @param {Function} [callback]
+ * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command
+ * @return {Query} this
+ * @api public
+ */
+
+Query.prototype.findOneAndUpdate = function(criteria, doc, options, callback) {
+ this.op = 'findOneAndUpdate';
+ this._validate();
+
+ switch (arguments.length) {
+ case 3:
+ if (typeof options === 'function') {
+ callback = options;
+ options = {};
+ }
+ break;
+ case 2:
+ if (typeof doc === 'function') {
+ callback = doc;
+ doc = criteria;
+ criteria = undefined;
+ }
+ options = undefined;
+ break;
+ case 1:
+ if (typeof criteria === 'function') {
+ callback = criteria;
+ criteria = options = doc = undefined;
+ } else {
+ doc = criteria;
+ criteria = options = undefined;
+ }
+ }
+
+ if (mquery.canMerge(criteria)) {
+ this.merge(criteria);
+ }
+
+ // apply doc
+ if (doc) {
+ this._mergeUpdate(doc);
+ }
+
+ if (options) {
+ options = utils.clone(options, { retainKeyOrder: true });
+ if (options.projection) {
+ this.select(options.projection);
+ delete options.projection;
+ }
+ if (options.fields) {
+ this.select(options.fields);
+ delete options.fields;
+ }
+
+ this.setOptions(options);
+ }
+
+ if (!callback) {
+ return this;
+ }
+
+ return this._findOneAndUpdate(callback);
+};
+
+/**
+ * Thunk around findOneAndUpdate()
+ *
+ * @param {Function} [callback]
+ * @api private
+ */
+
+Query.prototype._findOneAndUpdate = function(callback) {
+ this._findAndModify('update', callback);
+ return this;
+};
+
+/**
+ * Issues a mongodb [findAndModify](http://www.mongodb.org/display/DOCS/findAndModify+Command) remove command.
+ *
+ * Finds a matching document, removes it, passing the found document (if any) to the callback. Executes immediately if `callback` is passed.
+ *
+ * ####Available options
+ *
+ * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update
+ * - `maxTimeMS`: puts a time limit on the query - requires mongodb >= 2.6.0
+ * - `passRawResult`: if true, passes the [raw result from the MongoDB driver as the third callback parameter](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify)
+ *
+ * ####Callback Signature
+ * function(error, doc, result) {
+ * // error: any errors that occurred
+ * // doc: the document before updates are applied if `new: false`, or after updates if `new = true`
+ * // result: [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify)
+ * }
+ *
+ * ####Examples
+ *
+ * A.where().findOneAndRemove(conditions, options, callback) // executes
+ * A.where().findOneAndRemove(conditions, options) // return Query
+ * A.where().findOneAndRemove(conditions, callback) // executes
+ * A.where().findOneAndRemove(conditions) // returns Query
+ * A.where().findOneAndRemove(callback) // executes
+ * A.where().findOneAndRemove() // returns Query
+ *
+ * @method findOneAndRemove
+ * @memberOf Query
+ * @param {Object} [conditions]
+ * @param {Object} [options]
+ * @param {Function} [callback]
+ * @return {Query} this
+ * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command
+ * @api public
+ */
+
+Query.prototype.findOneAndRemove = function(conditions, options, callback) {
+ this.op = 'findOneAndRemove';
+ this._validate();
+
+ switch (arguments.length) {
+ case 2:
+ if (typeof options === 'function') {
+ callback = options;
+ options = {};
+ }
+ break;
+ case 1:
+ if (typeof conditions === 'function') {
+ callback = conditions;
+ conditions = undefined;
+ options = undefined;
+ }
+ break;
+ }
+
+ if (mquery.canMerge(conditions)) {
+ this.merge(conditions);
+ }
+
+ options && this.setOptions(options);
+
+ if (!callback) {
+ return this;
+ }
+
+ this._findOneAndRemove(callback);
+
+ return this;
+};
+
+/**
+ * Thunk around findOneAndRemove()
+ *
+ * @param {Function} [callback]
+ * @return {Query} this
+ * @api private
+ */
+Query.prototype._findOneAndRemove = function(callback) {
+ Query.base.findOneAndRemove.call(this, callback);
+};
+
+/**
+ * Override mquery.prototype._findAndModify to provide casting etc.
+ *
+ * @param {String} type - either "remove" or "update"
+ * @param {Function} callback
+ * @api private
+ */
+
+Query.prototype._findAndModify = function(type, callback) {
+ if (typeof callback !== 'function') {
+ throw new Error('Expected callback in _findAndModify');
+ }
+
+ var model = this.model;
+ var schema = model.schema;
+ var _this = this;
+ var castedQuery;
+ var castedDoc;
+ var fields;
+ var opts;
+ var doValidate;
+
+ castedQuery = castQuery(this);
+ if (castedQuery instanceof Error) {
+ return callback(castedQuery);
+ }
+
+ opts = this._optionsForExec(model);
+
+ if ('strict' in opts) {
+ this._mongooseOptions.strict = opts.strict;
+ }
+
+ if (type === 'remove') {
+ opts.remove = true;
+ } else {
+ if (!('new' in opts)) {
+ opts.new = false;
+ }
+ if (!('upsert' in opts)) {
+ opts.upsert = false;
+ }
+ if (opts.upsert || opts['new']) {
+ opts.remove = false;
+ }
+
+ castedDoc = castDoc(this, opts.overwrite);
+ castedDoc = setDefaultsOnInsert(this, schema, castedDoc, opts);
+ if (!castedDoc) {
+ if (opts.upsert) {
+ // still need to do the upsert to empty doc
+ var doc = utils.clone(castedQuery);
+ delete doc._id;
+ castedDoc = {$set: doc};
+ } else {
+ return this.findOne(callback);
+ }
+ } else if (castedDoc instanceof Error) {
+ return callback(castedDoc);
+ } else {
+ // In order to make MongoDB 2.6 happy (see
+ // https://jira.mongodb.org/browse/SERVER-12266 and related issues)
+ // if we have an actual update document but $set is empty, junk the $set.
+ if (castedDoc.$set && Object.keys(castedDoc.$set).length === 0) {
+ delete castedDoc.$set;
+ }
+ }
+
+ doValidate = updateValidators(this, schema, castedDoc, opts);
+ }
+
+ this._applyPaths();
+
+ var options = this._mongooseOptions;
+
+ if (this._fields) {
+ fields = utils.clone(this._fields);
+ opts.fields = this._castFields(fields);
+ if (opts.fields instanceof Error) {
+ return callback(opts.fields);
+ }
+ }
+
+ if (opts.sort) convertSortToArray(opts);
+
+ var cb = function(err, doc, res) {
+ if (err) {
+ return callback(err);
+ }
+
+ if (!doc || (utils.isObject(doc) && Object.keys(doc).length === 0)) {
+ if (opts.passRawResult) {
+ return callback(null, null, res);
+ }
+ return callback(null, null);
+ }
+
+ if (!opts.passRawResult) {
+ res = null;
+ }
+
+ if (!options.populate) {
+ return options.lean === true
+ ? callback(null, doc)
+ : completeOne(_this.model, doc, res, fields, _this, null, callback);
+ }
+
+ var pop = helpers.preparePopulationOptionsMQ(_this, options);
+ pop.__noPromise = true;
+ _this.model.populate(doc, pop, function(err, doc) {
+ if (err) {
+ return callback(err);
+ }
+
+ return options.lean === true
+ ? callback(null, doc)
+ : completeOne(_this.model, doc, res, fields, _this, pop, callback);
+ });
+ };
+
+ if (opts.runValidators && doValidate) {
+ var _callback = function(error) {
+ if (error) {
+ return callback(error);
+ }
+ _this._collection.findAndModify(castedQuery, castedDoc, opts, utils.tick(function(error, res) {
+ return cb(error, res ? res.value : res, res);
+ }));
+ };
+
+ try {
+ doValidate(_callback);
+ } catch (error) {
+ callback(error);
+ }
+ } else {
+ this._collection.findAndModify(castedQuery, castedDoc, opts, utils.tick(function(error, res) {
+ return cb(error, res ? res.value : res, res);
+ }));
+ }
+
+ return this;
+};
+
+/**
+ * Override mquery.prototype._mergeUpdate to handle mongoose objects in
+ * updates.
+ *
+ * @param {Object} doc
+ * @api private
+ */
+
+Query.prototype._mergeUpdate = function(doc) {
+ if (!this._update) this._update = {};
+ if (doc instanceof Query) {
+ if (doc._update) {
+ utils.mergeClone(this._update, doc._update);
+ }
+ } else {
+ utils.mergeClone(this._update, doc);
+ }
+};
+
+/*!
+ * The mongodb driver 1.3.23 only supports the nested array sort
+ * syntax. We must convert it or sorting findAndModify will not work.
+ */
+
+function convertSortToArray(opts) {
+ if (Array.isArray(opts.sort)) {
+ return;
+ }
+ if (!utils.isObject(opts.sort)) {
+ return;
+ }
+
+ var sort = [];
+
+ for (var key in opts.sort) {
+ if (utils.object.hasOwnProperty(opts.sort, key)) {
+ sort.push([key, opts.sort[key]]);
+ }
+ }
+
+ opts.sort = sort;
+}
+
+/**
+ * Internal thunk for .update()
+ *
+ * @param {Function} callback
+ * @see Model.update #model_Model.update
+ * @api private
+ */
+Query.prototype._execUpdate = function(callback) {
+ var schema = this.model.schema;
+ var doValidate;
+ var _this;
+
+ var castedQuery = this._conditions;
+ var castedDoc = this._update;
+ var options = this.options;
+
+ if (this._castError) {
+ callback(this._castError);
+ return this;
+ }
+
+ if (this.options.runValidators) {
+ _this = this;
+ doValidate = updateValidators(this, schema, castedDoc, options);
+ var _callback = function(err) {
+ if (err) {
+ return callback(err);
+ }
+
+ Query.base.update.call(_this, castedQuery, castedDoc, options, callback);
+ };
+ try {
+ doValidate(_callback);
+ } catch (err) {
+ process.nextTick(function() {
+ callback(err);
+ });
+ }
+ return this;
+ }
+
+ Query.base.update.call(this, castedQuery, castedDoc, options, callback);
+ return this;
+};
+
+/**
+ * Declare and/or execute this query as an update() operation.
+ *
+ * _All paths passed that are not $atomic operations will become $set ops._
+ *
+ * ####Example
+ *
+ * Model.where({ _id: id }).update({ title: 'words' })
+ *
+ * // becomes
+ *
+ * Model.where({ _id: id }).update({ $set: { title: 'words' }})
+ *
+ * ####Valid options:
+ *
+ * - `safe` (boolean) safe mode (defaults to value set in schema (true))
+ * - `upsert` (boolean) whether to create the doc if it doesn't match (false)
+ * - `multi` (boolean) whether multiple documents should be updated (false)
+ * - `runValidators`: if true, runs [update validators](/docs/validation.html#update-validators) on this command. Update validators validate the update operation against the model's schema.
+ * - `setDefaultsOnInsert`: if this and `upsert` are true, mongoose will apply the [defaults](http://mongoosejs.com/docs/defaults.html) specified in the model's schema if a new document is created. This option only works on MongoDB >= 2.4 because it relies on [MongoDB's `$setOnInsert` operator](https://docs.mongodb.org/v2.4/reference/operator/update/setOnInsert/).
+ * - `strict` (boolean) overrides the `strict` option for this update
+ * - `overwrite` (boolean) disables update-only mode, allowing you to overwrite the doc (false)
+ * - `context` (string) if set to 'query' and `runValidators` is on, `this` will refer to the query in custom validator functions that update validation runs. Does nothing if `runValidators` is false.
+ *
+ * ####Note
+ *
+ * Passing an empty object `{}` as the doc will result in a no-op unless the `overwrite` option is passed. Without the `overwrite` option set, the update operation will be ignored and the callback executed without sending the command to MongoDB so as to prevent accidently overwritting documents in the collection.
+ *
+ * ####Note
+ *
+ * The operation is only executed when a callback is passed. To force execution without a callback, we must first call update() and then execute it by using the `exec()` method.
+ *
+ * var q = Model.where({ _id: id });
+ * q.update({ $set: { name: 'bob' }}).update(); // not executed
+ *
+ * q.update({ $set: { name: 'bob' }}).exec(); // executed
+ *
+ * // keys that are not $atomic ops become $set.
+ * // this executes the same command as the previous example.
+ * q.update({ name: 'bob' }).exec();
+ *
+ * // overwriting with empty docs
+ * var q = Model.where({ _id: id }).setOptions({ overwrite: true })
+ * q.update({ }, callback); // executes
+ *
+ * // multi update with overwrite to empty doc
+ * var q = Model.where({ _id: id });
+ * q.setOptions({ multi: true, overwrite: true })
+ * q.update({ });
+ * q.update(callback); // executed
+ *
+ * // multi updates
+ * Model.where()
+ * .update({ name: /^match/ }, { $set: { arr: [] }}, { multi: true }, callback)
+ *
+ * // more multi updates
+ * Model.where()
+ * .setOptions({ multi: true })
+ * .update({ $set: { arr: [] }}, callback)
+ *
+ * // single update by default
+ * Model.where({ email: 'address@example.com' })
+ * .update({ $inc: { counter: 1 }}, callback)
+ *
+ * API summary
+ *
+ * update(criteria, doc, options, cb) // executes
+ * update(criteria, doc, options)
+ * update(criteria, doc, cb) // executes
+ * update(criteria, doc)
+ * update(doc, cb) // executes
+ * update(doc)
+ * update(cb) // executes
+ * update(true) // executes
+ * update()
+ *
+ * @param {Object} [criteria]
+ * @param {Object} [doc] the update command
+ * @param {Object} [options]
+ * @param {Function} [callback]
+ * @return {Query} this
+ * @see Model.update #model_Model.update
+ * @see update http://docs.mongodb.org/manual/reference/method/db.collection.update/
+ * @api public
+ */
+
+Query.prototype.update = function(conditions, doc, options, callback) {
+ if (typeof options === 'function') {
+ // .update(conditions, doc, callback)
+ callback = options;
+ options = null;
+ } else if (typeof doc === 'function') {
+ // .update(doc, callback);
+ callback = doc;
+ doc = conditions;
+ conditions = {};
+ options = null;
+ } else if (typeof conditions === 'function') {
+ // .update(callback)
+ callback = conditions;
+ conditions = undefined;
+ doc = undefined;
+ options = undefined;
+ } else if (typeof conditions === 'object' && !doc && !options && !callback) {
+ // .update(doc)
+ doc = conditions;
+ conditions = undefined;
+ options = undefined;
+ callback = undefined;
+ }
+
+ // make sure we don't send in the whole Document to merge()
+ conditions = utils.toObject(conditions);
+
+ var oldCb = callback;
+ if (oldCb) {
+ if (typeof oldCb === 'function') {
+ callback = function(error, result) {
+ oldCb(error, result ? result.result : {ok: 0, n: 0, nModified: 0});
+ };
+ } else {
+ throw new Error('Invalid callback() argument.');
+ }
+ }
+
+ // strict is an option used in the update checking, make sure it gets set
+ if (options) {
+ if ('strict' in options) {
+ this._mongooseOptions.strict = options.strict;
+ }
+ }
+
+ // if doc is undefined at this point, this means this function is being
+ // executed by exec(not always see below). Grab the update doc from here in
+ // order to validate
+ // This could also be somebody calling update() or update({}). Probably not a
+ // common use case, check for _update to make sure we don't do anything bad
+ if (!doc && this._update) {
+ doc = this._updateForExec();
+ }
+
+ if (mquery.canMerge(conditions)) {
+ this.merge(conditions);
+ }
+
+ // validate the selector part of the query
+ var castedQuery = castQuery(this);
+ if (castedQuery instanceof Error) {
+ this._castError = castedQuery;
+ if (callback) {
+ callback(castedQuery);
+ return this;
+ } else if (!options || !options.dontThrowCastError) {
+ throw castedQuery;
+ }
+ }
+
+ // validate the update part of the query
+ var castedDoc;
+ try {
+ var $options = {retainKeyOrder: true};
+ if (options && options.minimize) {
+ $options.minimize = true;
+ }
+ castedDoc = this._castUpdate(utils.clone(doc, $options),
+ options && options.overwrite);
+ } catch (err) {
+ this._castError = castedQuery;
+ if (callback) {
+ callback(err);
+ return this;
+ } else if (!options || !options.dontThrowCastError) {
+ throw err;
+ }
+ }
+
+ castedDoc = setDefaultsOnInsert(this, this.schema, castedDoc, options);
+ if (!castedDoc) {
+ // Make sure promises know that this is still an update, see gh-2796
+ this.op = 'update';
+ callback && callback(null);
+ return this;
+ }
+
+ if (utils.isObject(options)) {
+ this.setOptions(options);
+ }
+
+ if (!this._update) this._update = castedDoc;
+
+ // Hooks
+ if (callback) {
+ return this._execUpdate(callback);
+ }
+
+ return Query.base.update.call(this, castedQuery, castedDoc, options, callback);
+};
+
+/**
+ * Executes the query
+ *
+ * ####Examples:
+ *
+ * var promise = query.exec();
+ * var promise = query.exec('update');
+ *
+ * query.exec(callback);
+ * query.exec('find', callback);
+ *
+ * @param {String|Function} [operation]
+ * @param {Function} [callback]
+ * @return {Promise}
+ * @api public
+ */
+
+Query.prototype.exec = function exec(op, callback) {
+ var Promise = PromiseProvider.get();
+ var _this = this;
+
+ if (typeof op === 'function') {
+ callback = op;
+ op = null;
+ } else if (typeof op === 'string') {
+ this.op = op;
+ }
+
+ var _results;
+ var promise = new Promise.ES6(function(resolve, reject) {
+ if (!_this.op) {
+ resolve();
+ return;
+ }
+
+ _this[_this.op].call(_this, function(error, res) {
+ if (error) {
+ reject(error);
+ return;
+ }
+ _results = arguments;
+ resolve(res);
+ });
+ });
+
+ if (callback) {
+ promise.then(
+ function() {
+ callback.apply(null, _results);
+ },
+ function(error) {
+ callback(error);
+ }).
+ catch(function(error) {
+ // If we made it here, we must have an error in the callback re:
+ // gh-4500, so we need to emit.
+ setImmediate(function() {
+ _this.model.emit('error', error);
+ });
+ });
+ }
+
+ return promise;
+};
+
+/**
+ * Executes the query returning a `Promise` which will be
+ * resolved with either the doc(s) or rejected with the error.
+ *
+ * @param {Function} [resolve]
+ * @param {Function} [reject]
+ * @return {Promise}
+ * @api public
+ */
+
+Query.prototype.then = function(resolve, reject) {
+ return this.exec().then(resolve, reject);
+};
+
+/**
+ * Executes the query returning a `Promise` which will be
+ * resolved with either the doc(s) or rejected with the error.
+ * Like `.then()`, but only takes a rejection handler.
+ *
+ * @param {Function} [reject]
+ * @return {Promise}
+ * @api public
+ */
+
+Query.prototype.catch = function(reject) {
+ return this.exec().then(null, reject);
+};
+
+/**
+ * Finds the schema for `path`. This is different than
+ * calling `schema.path` as it also resolves paths with
+ * positional selectors (something.$.another.$.path).
+ *
+ * @param {String} path
+ * @api private
+ */
+
+Query.prototype._getSchema = function _getSchema(path) {
+ return this.model._getSchema(path);
+};
+
+/*!
+ * These operators require casting docs
+ * to real Documents for Update operations.
+ */
+
+var castOps = {
+ $push: 1,
+ $pushAll: 1,
+ $addToSet: 1,
+ $set: 1
+};
+
+/*!
+ * These operators should be cast to numbers instead
+ * of their path schema type.
+ */
+
+var numberOps = {
+ $pop: 1,
+ $unset: 1,
+ $inc: 1
+};
+
+/**
+ * Casts obj for an update command.
+ *
+ * @param {Object} obj
+ * @return {Object} obj after casting its values
+ * @api private
+ */
+
+Query.prototype._castUpdate = function _castUpdate(obj, overwrite) {
+ if (!obj) {
+ return undefined;
+ }
+
+ var ops = Object.keys(obj);
+ var i = ops.length;
+ var ret = {};
+ var hasKeys;
+ var val;
+ var hasDollarKey = false;
+
+ while (i--) {
+ var op = ops[i];
+ // if overwrite is set, don't do any of the special $set stuff
+ if (op[0] !== '$' && !overwrite) {
+ // fix up $set sugar
+ if (!ret.$set) {
+ if (obj.$set) {
+ ret.$set = obj.$set;
+ } else {
+ ret.$set = {};
+ }
+ }
+ ret.$set[op] = obj[op];
+ ops.splice(i, 1);
+ if (!~ops.indexOf('$set')) ops.push('$set');
+ } else if (op === '$set') {
+ if (!ret.$set) {
+ ret[op] = obj[op];
+ }
+ } else {
+ ret[op] = obj[op];
+ }
+ }
+
+ // cast each value
+ i = ops.length;
+
+ // if we get passed {} for the update, we still need to respect that when it
+ // is an overwrite scenario
+ if (overwrite) {
+ hasKeys = true;
+ }
+
+ while (i--) {
+ op = ops[i];
+ val = ret[op];
+ hasDollarKey = hasDollarKey || op.charAt(0) === '$';
+ if (val &&
+ val.constructor.name === 'Object' &&
+ (!overwrite || hasDollarKey)) {
+ hasKeys |= this._walkUpdatePath(val, op);
+ } else if (overwrite && ret.constructor.name === 'Object') {
+ // if we are just using overwrite, cast the query and then we will
+ // *always* return the value, even if it is an empty object. We need to
+ // set hasKeys above because we need to account for the case where the
+ // user passes {} and wants to clobber the whole document
+ // Also, _walkUpdatePath expects an operation, so give it $set since that
+ // is basically what we're doing
+ this._walkUpdatePath(ret, '$set');
+ } else {
+ var msg = 'Invalid atomic update value for ' + op + '. '
+ + 'Expected an object, received ' + typeof val;
+ throw new Error(msg);
+ }
+ }
+
+ return hasKeys && ret;
+};
+
+/**
+ * Walk each path of obj and cast its values
+ * according to its schema.
+ *
+ * @param {Object} obj - part of a query
+ * @param {String} op - the atomic operator ($pull, $set, etc)
+ * @param {String} pref - path prefix (internal only)
+ * @return {Bool} true if this path has keys to update
+ * @api private
+ */
+
+Query.prototype._walkUpdatePath = function _walkUpdatePath(obj, op, pref) {
+ var prefix = pref ? pref + '.' : '',
+ keys = Object.keys(obj),
+ i = keys.length,
+ hasKeys = false,
+ schema,
+ key,
+ val;
+
+ var useNestedStrict = this.schema.options.useNestedStrict;
+
+ while (i--) {
+ key = keys[i];
+ val = obj[key];
+
+ if (val && val.constructor.name === 'Object') {
+ // watch for embedded doc schemas
+ schema = this._getSchema(prefix + key);
+ if (schema && schema.caster && op in castOps) {
+ // embedded doc schema
+ hasKeys = true;
+
+ if ('$each' in val) {
+ obj[key] = {
+ $each: this._castUpdateVal(schema, val.$each, op)
+ };
+
+ if (val.$slice != null) {
+ obj[key].$slice = val.$slice | 0;
+ }
+
+ if (val.$sort) {
+ obj[key].$sort = val.$sort;
+ }
+
+ if (!!val.$position || val.$position === 0) {
+ obj[key].$position = val.$position;
+ }
+ } else {
+ obj[key] = this._castUpdateVal(schema, val, op);
+ }
+ } else if (op === '$currentDate') {
+ // $currentDate can take an object
+ obj[key] = this._castUpdateVal(schema, val, op);
+ hasKeys = true;
+ } else if (op === '$set' && schema) {
+ obj[key] = this._castUpdateVal(schema, val, op);
+ hasKeys = true;
+ } else {
+ var pathToCheck = (prefix + key);
+ var v = this.model.schema._getPathType(pathToCheck);
+ var _strict = 'strict' in this._mongooseOptions ?
+ this._mongooseOptions.strict :
+ ((useNestedStrict && v.schema) || this.schema).options.strict;
+ if (v.pathType === 'undefined') {
+ if (_strict === 'throw') {
+ throw new StrictModeError(pathToCheck);
+ } else if (_strict) {
+ delete obj[key];
+ continue;
+ }
+ }
+
+ // gh-2314
+ // we should be able to set a schema-less field
+ // to an empty object literal
+ hasKeys |= this._walkUpdatePath(val, op, prefix + key) ||
+ (utils.isObject(val) && Object.keys(val).length === 0);
+ }
+ } else {
+ var checkPath = (key === '$each' || key === '$or' || key === '$and') ?
+ pref : prefix + key;
+ schema = this._getSchema(checkPath);
+
+ var pathDetails = this.model.schema._getPathType(checkPath);
+ var isStrict = 'strict' in this._mongooseOptions ?
+ this._mongooseOptions.strict :
+ ((useNestedStrict && pathDetails.schema) || this.schema).options.strict;
+
+ var skip = isStrict &&
+ !schema &&
+ !/real|nested/.test(pathDetails.pathType);
+
+ if (skip) {
+ if (isStrict === 'throw') {
+ throw new StrictModeError(prefix + key);
+ } else {
+ delete obj[key];
+ }
+ } else {
+ // gh-1845 temporary fix: ignore $rename. See gh-3027 for tracking
+ // improving this.
+ if (op === '$rename') {
+ hasKeys = true;
+ continue;
+ }
+
+ hasKeys = true;
+ obj[key] = this._castUpdateVal(schema, val, op, key);
+ }
+ }
+ }
+ return hasKeys;
+};
+
+/**
+ * Casts `val` according to `schema` and atomic `op`.
+ *
+ * @param {Schema} schema
+ * @param {Object} val
+ * @param {String} op - the atomic operator ($pull, $set, etc)
+ * @param {String} [$conditional]
+ * @api private
+ */
+
+Query.prototype._castUpdateVal = function _castUpdateVal(schema, val, op, $conditional) {
+ if (!schema) {
+ // non-existing schema path
+ return op in numberOps
+ ? Number(val)
+ : val;
+ }
+
+ var cond = schema.caster && op in castOps &&
+ (utils.isObject(val) || Array.isArray(val));
+ if (cond) {
+ // Cast values for ops that add data to MongoDB.
+ // Ensures embedded documents get ObjectIds etc.
+ var tmp = schema.cast(val);
+ if (Array.isArray(val)) {
+ val = tmp;
+ } else if (Array.isArray(tmp)) {
+ val = tmp[0];
+ } else {
+ val = tmp;
+ }
+ }
+
+ if (op in numberOps) {
+ if (op === '$inc') {
+ return schema.castForQuery(val);
+ }
+ return Number(val);
+ }
+ if (op === '$currentDate') {
+ if (typeof val === 'object') {
+ return {$type: val.$type};
+ }
+ return Boolean(val);
+ }
+ if (/^\$/.test($conditional)) {
+ return schema.castForQuery($conditional, val);
+ }
+
+ return schema.castForQuery(val);
+};
+
+/*!
+ * castQuery
+ * @api private
+ */
+
+function castQuery(query) {
+ try {
+ return query.cast(query.model);
+ } catch (err) {
+ return err;
+ }
+}
+
+/*!
+ * castDoc
+ * @api private
+ */
+
+function castDoc(query, overwrite) {
+ try {
+ return query._castUpdate(query._update, overwrite);
+ } catch (err) {
+ return err;
+ }
+}
+
+/**
+ * Specifies paths which should be populated with other documents.
+ *
+ * ####Example:
+ *
+ * Kitten.findOne().populate('owner').exec(function (err, kitten) {
+ * console.log(kitten.owner.name) // Max
+ * })
+ *
+ * Kitten.find().populate({
+ * path: 'owner'
+ * , select: 'name'
+ * , match: { color: 'black' }
+ * , options: { sort: { name: -1 }}
+ * }).exec(function (err, kittens) {
+ * console.log(kittens[0].owner.name) // Zoopa
+ * })
+ *
+ * // alternatively
+ * Kitten.find().populate('owner', 'name', null, {sort: { name: -1 }}).exec(function (err, kittens) {
+ * console.log(kittens[0].owner.name) // Zoopa
+ * })
+ *
+ * Paths are populated after the query executes and a response is received. A separate query is then executed for each path specified for population. After a response for each query has also been returned, the results are passed to the callback.
+ *
+ * @param {Object|String} path either the path to populate or an object specifying all parameters
+ * @param {Object|String} [select] Field selection for the population query
+ * @param {Model} [model] The model you wish to use for population. If not specified, populate will look up the model by the name in the Schema's `ref` field.
+ * @param {Object} [match] Conditions for the population query
+ * @param {Object} [options] Options for the population query (sort, etc)
+ * @see population ./populate.html
+ * @see Query#select #query_Query-select
+ * @see Model.populate #model_Model.populate
+ * @return {Query} this
+ * @api public
+ */
+
+Query.prototype.populate = function() {
+ var res = utils.populate.apply(null, arguments);
+ var opts = this._mongooseOptions;
+
+ if (!utils.isObject(opts.populate)) {
+ opts.populate = {};
+ }
+
+ var pop = opts.populate;
+
+ for (var i = 0; i < res.length; ++i) {
+ var path = res[i].path;
+ if (pop[path] && pop[path].populate && res[i].populate) {
+ res[i].populate = pop[path].populate.concat(res[i].populate);
+ }
+ pop[res[i].path] = res[i];
+ }
+
+ return this;
+};
+
+/**
+ * Casts this query to the schema of `model`
+ *
+ * ####Note
+ *
+ * If `obj` is present, it is cast instead of this query.
+ *
+ * @param {Model} model
+ * @param {Object} [obj]
+ * @return {Object}
+ * @api public
+ */
+
+Query.prototype.cast = function(model, obj) {
+ obj || (obj = this._conditions);
+
+ try {
+ return cast(model.schema, obj);
+ } catch (err) {
+ // CastError, assign model
+ if (typeof err.setModel === 'function') {
+ err.setModel(model);
+ }
+ throw err;
+ }
+};
+
+/**
+ * Casts selected field arguments for field selection with mongo 2.2
+ *
+ * query.select({ ids: { $elemMatch: { $in: [hexString] }})
+ *
+ * @param {Object} fields
+ * @see https://github.com/Automattic/mongoose/issues/1091
+ * @see http://docs.mongodb.org/manual/reference/projection/elemMatch/
+ * @api private
+ */
+
+Query.prototype._castFields = function _castFields(fields) {
+ var selected,
+ elemMatchKeys,
+ keys,
+ key,
+ out,
+ i;
+
+ if (fields) {
+ keys = Object.keys(fields);
+ elemMatchKeys = [];
+ i = keys.length;
+
+ // collect $elemMatch args
+ while (i--) {
+ key = keys[i];
+ if (fields[key].$elemMatch) {
+ selected || (selected = {});
+ selected[key] = fields[key];
+ elemMatchKeys.push(key);
+ }
+ }
+ }
+
+ if (selected) {
+ // they passed $elemMatch, cast em
+ try {
+ out = this.cast(this.model, selected);
+ } catch (err) {
+ return err;
+ }
+
+ // apply the casted field args
+ i = elemMatchKeys.length;
+ while (i--) {
+ key = elemMatchKeys[i];
+ fields[key] = out[key];
+ }
+ }
+
+ return fields;
+};
+
+/**
+ * Applies schematype selected options to this query.
+ * @api private
+ */
+
+Query.prototype._applyPaths = function applyPaths() {
+ // determine if query is selecting or excluding fields
+
+ var fields = this._fields,
+ exclude,
+ keys,
+ ki;
+
+ if (fields) {
+ keys = Object.keys(fields);
+ ki = keys.length;
+
+ while (ki--) {
+ if (keys[ki][0] === '+') continue;
+ exclude = fields[keys[ki]] === 0;
+ break;
+ }
+ }
+
+ // if selecting, apply default schematype select:true fields
+ // if excluding, apply schematype select:false fields
+
+ var selected = [],
+ excluded = [],
+ seen = [];
+
+ var analyzePath = function(path, type) {
+ if (typeof type.selected !== 'boolean') return;
+
+ var plusPath = '+' + path;
+ if (fields && plusPath in fields) {
+ // forced inclusion
+ delete fields[plusPath];
+
+ // if there are other fields being included, add this one
+ // if no other included fields, leave this out (implied inclusion)
+ if (exclude === false && keys.length > 1 && !~keys.indexOf(path)) {
+ fields[path] = 1;
+ }
+
+ return;
+ }
+
+ // check for parent exclusions
+ var root = path.split('.')[0];
+ if (~excluded.indexOf(root)) return;
+
+ (type.selected ? selected : excluded).push(path);
+ };
+
+ var analyzeSchema = function(schema, prefix) {
+ prefix || (prefix = '');
+
+ // avoid recursion
+ if (~seen.indexOf(schema)) return;
+ seen.push(schema);
+
+ schema.eachPath(function(path, type) {
+ if (prefix) path = prefix + '.' + path;
+
+ analyzePath(path, type);
+
+ // array of subdocs?
+ if (type.schema) {
+ analyzeSchema(type.schema, path);
+ }
+ });
+ };
+
+ analyzeSchema(this.model.schema);
+
+ switch (exclude) {
+ case true:
+ excluded.length && this.select('-' + excluded.join(' -'));
+ break;
+ case false:
+ if (this.model.schema && this.model.schema.paths['_id'] &&
+ this.model.schema.paths['_id'].options && this.model.schema.paths['_id'].options.select === false) {
+ selected.push('-_id');
+ }
+ selected.length && this.select(selected.join(' '));
+ break;
+ case undefined:
+ // user didn't specify fields, implies returning all fields.
+ // only need to apply excluded fields
+ excluded.length && this.select('-' + excluded.join(' -'));
+ break;
+ }
+ seen = excluded = selected = keys = fields = null;
+};
+
+/**
+ * Returns a Node.js 0.8 style [read stream](http://nodejs.org/docs/v0.8.21/api/stream.html#stream_readable_stream) interface.
+ *
+ * ####Example
+ *
+ * // follows the nodejs 0.8 stream api
+ * Thing.find({ name: /^hello/ }).stream().pipe(res)
+ *
+ * // manual streaming
+ * var stream = Thing.find({ name: /^hello/ }).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
+ * });
+ *
+ * ####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);
+ *
+ * @return {QueryStream}
+ * @param {Object} [options]
+ * @see QueryStream
+ * @api public
+ */
+
+Query.prototype.stream = function stream(opts) {
+ this._applyPaths();
+ this._fields = this._castFields(this._fields);
+ return new QueryStream(this, opts);
+};
+Query.prototype.stream = util.deprecate(Query.prototype.stream, 'Mongoose: ' +
+ 'Query.prototype.stream() is deprecated in mongoose >= 4.5.0, ' +
+ 'use Query.prototype.cursor() instead');
+
+/**
+ * Returns a wrapper around a [mongodb driver cursor](http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html).
+ * A QueryCursor exposes a [Streams3](https://strongloop.com/strongblog/whats-new-io-js-beta-streams3/)-compatible
+ * interface, as well as a `.next()` function.
+ *
+ * ####Example
+ *
+ * // There are 2 ways to use a cursor. First, as a stream:
+ * Thing.
+ * find({ name: /^hello/ }).
+ * cursor().
+ * on('data', function(doc) { console.log(doc); }).
+ * on('end', function() { console.log('Done!'); });
+ *
+ * // Or you can use `.next()` to manually get the next doc in the stream.
+ * // `.next()` returns a promise, so you can use promises or callbacks.
+ * var cursor = Thing.find({ name: /^hello/ }).cursor();
+ * cursor.next(function(error, doc) {
+ * console.log(doc);
+ * });
+ *
+ * // Because `.next()` returns a promise, you can use co
+ * // to easily iterate through all documents without loading them
+ * // all into memory.
+ * co(function*() {
+ * const cursor = Thing.find({ name: /^hello/ }).cursor();
+ * for (let doc = yield cursor.next(); doc != null; doc = yield cursor.next()) {
+ * console.log(doc);
+ * }
+ * });
+ *
+ * ####Valid options
+ *
+ * - `transform`: optional function which accepts a mongoose document. The return value of the function will be emitted on `data` and returned by `.next()`.
+ *
+ * @return {QueryCursor}
+ * @param {Object} [options]
+ * @see QueryCursor
+ * @api public
+ */
+
+Query.prototype.cursor = function cursor(opts) {
+ this._applyPaths();
+ this._fields = this._castFields(this._fields);
+ this.setOptions({ fields: this._fieldsForExec() });
+ if (opts) {
+ this.setOptions(opts);
+ }
+
+ try {
+ this.cast(this.model);
+ } catch (err) {
+ return (new QueryCursor(this, this.options))._markError(err);
+ }
+
+ return new QueryCursor(this, this.options);
+};
+
+// the rest of these are basically to support older Mongoose syntax with mquery
+
+/**
+ * _DEPRECATED_ Alias of `maxScan`
+ *
+ * @deprecated
+ * @see maxScan #query_Query-maxScan
+ * @method maxscan
+ * @memberOf Query
+ */
+
+Query.prototype.maxscan = Query.base.maxScan;
+
+/**
+ * Sets the tailable option (for use with capped collections).
+ *
+ * ####Example
+ *
+ * query.tailable() // true
+ * query.tailable(true)
+ * query.tailable(false)
+ *
+ * ####Note
+ *
+ * Cannot be used with `distinct()`
+ *
+ * @param {Boolean} bool defaults to true
+ * @param {Object} [opts] options to set
+ * @param {Number} [opts.numberOfRetries] if cursor is exhausted, retry this many times before giving up
+ * @param {Number} [opts.tailableRetryInterval] if cursor is exhausted, wait this many milliseconds before retrying
+ * @see tailable http://docs.mongodb.org/manual/tutorial/create-tailable-cursor/
+ * @api public
+ */
+
+Query.prototype.tailable = function(val, opts) {
+ // we need to support the tailable({ awaitdata : true }) as well as the
+ // tailable(true, {awaitdata :true}) syntax that mquery does not support
+ if (val && val.constructor.name === 'Object') {
+ opts = val;
+ val = true;
+ }
+
+ if (val === undefined) {
+ val = true;
+ }
+
+ if (opts && typeof opts === 'object') {
+ for (var key in opts) {
+ if (key === 'awaitdata') {
+ // For backwards compatibility
+ this.options[key] = !!opts[key];
+ } else {
+ this.options[key] = opts[key];
+ }
+ }
+ }
+
+ return Query.base.tailable.call(this, val);
+};
+
+/**
+ * Declares an intersects query for `geometry()`.
+ *
+ * ####Example
+ *
+ * query.where('path').intersects().geometry({
+ * type: 'LineString'
+ * , coordinates: [[180.0, 11.0], [180, 9.0]]
+ * })
+ *
+ * query.where('path').intersects({
+ * type: 'LineString'
+ * , coordinates: [[180.0, 11.0], [180, 9.0]]
+ * })
+ *
+ * ####NOTE:
+ *
+ * **MUST** be used after `where()`.
+ *
+ * ####NOTE:
+ *
+ * In Mongoose 3.7, `intersects` changed from a getter to a function. If you need the old syntax, use [this](https://github.com/ebensing/mongoose-within).
+ *
+ * @method intersects
+ * @memberOf Query
+ * @param {Object} [arg]
+ * @return {Query} this
+ * @see $geometry http://docs.mongodb.org/manual/reference/operator/geometry/
+ * @see geoIntersects http://docs.mongodb.org/manual/reference/operator/geoIntersects/
+ * @api public
+ */
+
+/**
+ * Specifies a `$geometry` condition
+ *
+ * ####Example
+ *
+ * var polyA = [[[ 10, 20 ], [ 10, 40 ], [ 30, 40 ], [ 30, 20 ]]]
+ * query.where('loc').within().geometry({ type: 'Polygon', coordinates: polyA })
+ *
+ * // or
+ * var polyB = [[ 0, 0 ], [ 1, 1 ]]
+ * query.where('loc').within().geometry({ type: 'LineString', coordinates: polyB })
+ *
+ * // or
+ * var polyC = [ 0, 0 ]
+ * query.where('loc').within().geometry({ type: 'Point', coordinates: polyC })
+ *
+ * // or
+ * query.where('loc').intersects().geometry({ type: 'Point', coordinates: polyC })
+ *
+ * The argument is assigned to the most recent path passed to `where()`.
+ *
+ * ####NOTE:
+ *
+ * `geometry()` **must** come after either `intersects()` or `within()`.
+ *
+ * The `object` argument must contain `type` and `coordinates` properties.
+ * - type {String}
+ * - coordinates {Array}
+ *
+ * @method geometry
+ * @memberOf Query
+ * @param {Object} object Must contain a `type` property which is a String and a `coordinates` property which is an Array. See the examples.
+ * @return {Query} this
+ * @see $geometry http://docs.mongodb.org/manual/reference/operator/geometry/
+ * @see http://docs.mongodb.org/manual/release-notes/2.4/#new-geospatial-indexes-with-geojson-and-improved-spherical-geometry
+ * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing
+ * @api public
+ */
+
+/**
+ * Specifies a `$near` or `$nearSphere` condition
+ *
+ * These operators return documents sorted by distance.
+ *
+ * ####Example
+ *
+ * query.where('loc').near({ center: [10, 10] });
+ * query.where('loc').near({ center: [10, 10], maxDistance: 5 });
+ * query.where('loc').near({ center: [10, 10], maxDistance: 5, spherical: true });
+ * query.near('loc', { center: [10, 10], maxDistance: 5 });
+ *
+ * @method near
+ * @memberOf Query
+ * @param {String} [path]
+ * @param {Object} val
+ * @return {Query} this
+ * @see $near http://docs.mongodb.org/manual/reference/operator/near/
+ * @see $nearSphere http://docs.mongodb.org/manual/reference/operator/nearSphere/
+ * @see $maxDistance http://docs.mongodb.org/manual/reference/operator/maxDistance/
+ * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing
+ * @api public
+ */
+
+/*!
+ * Overwriting mquery is needed to support a couple different near() forms found in older
+ * versions of mongoose
+ * near([1,1])
+ * near(1,1)
+ * near(field, [1,2])
+ * near(field, 1, 2)
+ * In addition to all of the normal forms supported by mquery
+ */
+
+Query.prototype.near = function() {
+ var params = [];
+ var sphere = this._mongooseOptions.nearSphere;
+
+ // TODO refactor
+
+ if (arguments.length === 1) {
+ if (Array.isArray(arguments[0])) {
+ params.push({center: arguments[0], spherical: sphere});
+ } else if (typeof arguments[0] === 'string') {
+ // just passing a path
+ params.push(arguments[0]);
+ } else if (utils.isObject(arguments[0])) {
+ if (typeof arguments[0].spherical !== 'boolean') {
+ arguments[0].spherical = sphere;
+ }
+ params.push(arguments[0]);
+ } else {
+ throw new TypeError('invalid argument');
+ }
+ } else if (arguments.length === 2) {
+ if (typeof arguments[0] === 'number' && typeof arguments[1] === 'number') {
+ params.push({center: [arguments[0], arguments[1]], spherical: sphere});
+ } else if (typeof arguments[0] === 'string' && Array.isArray(arguments[1])) {
+ params.push(arguments[0]);
+ params.push({center: arguments[1], spherical: sphere});
+ } else if (typeof arguments[0] === 'string' && utils.isObject(arguments[1])) {
+ params.push(arguments[0]);
+ if (typeof arguments[1].spherical !== 'boolean') {
+ arguments[1].spherical = sphere;
+ }
+ params.push(arguments[1]);
+ } else {
+ throw new TypeError('invalid argument');
+ }
+ } else if (arguments.length === 3) {
+ if (typeof arguments[0] === 'string' && typeof arguments[1] === 'number'
+ && typeof arguments[2] === 'number') {
+ params.push(arguments[0]);
+ params.push({center: [arguments[1], arguments[2]], spherical: sphere});
+ } else {
+ throw new TypeError('invalid argument');
+ }
+ } else {
+ throw new TypeError('invalid argument');
+ }
+
+ return Query.base.near.apply(this, params);
+};
+
+/**
+ * _DEPRECATED_ Specifies a `$nearSphere` condition
+ *
+ * ####Example
+ *
+ * query.where('loc').nearSphere({ center: [10, 10], maxDistance: 5 });
+ *
+ * **Deprecated.** Use `query.near()` instead with the `spherical` option set to `true`.
+ *
+ * ####Example
+ *
+ * query.where('loc').near({ center: [10, 10], spherical: true });
+ *
+ * @deprecated
+ * @see near() #query_Query-near
+ * @see $near http://docs.mongodb.org/manual/reference/operator/near/
+ * @see $nearSphere http://docs.mongodb.org/manual/reference/operator/nearSphere/
+ * @see $maxDistance http://docs.mongodb.org/manual/reference/operator/maxDistance/
+ */
+
+Query.prototype.nearSphere = function() {
+ this._mongooseOptions.nearSphere = true;
+ this.near.apply(this, arguments);
+ return this;
+};
+
+/**
+ * Specifies a $polygon condition
+ *
+ * ####Example
+ *
+ * query.where('loc').within().polygon([10,20], [13, 25], [7,15])
+ * query.polygon('loc', [10,20], [13, 25], [7,15])
+ *
+ * @method polygon
+ * @memberOf Query
+ * @param {String|Array} [path]
+ * @param {Array|Object} [coordinatePairs...]
+ * @return {Query} this
+ * @see $polygon http://docs.mongodb.org/manual/reference/operator/polygon/
+ * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing
+ * @api public
+ */
+
+/**
+ * Specifies a $box condition
+ *
+ * ####Example
+ *
+ * var lowerLeft = [40.73083, -73.99756]
+ * var upperRight= [40.741404, -73.988135]
+ *
+ * query.where('loc').within().box(lowerLeft, upperRight)
+ * query.box({ ll : lowerLeft, ur : upperRight })
+ *
+ * @method box
+ * @memberOf Query
+ * @see $box http://docs.mongodb.org/manual/reference/operator/box/
+ * @see within() Query#within #query_Query-within
+ * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing
+ * @param {Object} val
+ * @param [Array] Upper Right Coords
+ * @return {Query} this
+ * @api public
+ */
+
+/*!
+ * this is needed to support the mongoose syntax of:
+ * box(field, { ll : [x,y], ur : [x2,y2] })
+ * box({ ll : [x,y], ur : [x2,y2] })
+ */
+
+Query.prototype.box = function(ll, ur) {
+ if (!Array.isArray(ll) && utils.isObject(ll)) {
+ ur = ll.ur;
+ ll = ll.ll;
+ }
+ return Query.base.box.call(this, ll, ur);
+};
+
+/**
+ * Specifies a $center or $centerSphere condition.
+ *
+ * ####Example
+ *
+ * var area = { center: [50, 50], radius: 10, unique: true }
+ * query.where('loc').within().circle(area)
+ * // alternatively
+ * query.circle('loc', area);
+ *
+ * // spherical calculations
+ * var area = { center: [50, 50], radius: 10, unique: true, spherical: true }
+ * query.where('loc').within().circle(area)
+ * // alternatively
+ * query.circle('loc', area);
+ *
+ * New in 3.7.0
+ *
+ * @method circle
+ * @memberOf Query
+ * @param {String} [path]
+ * @param {Object} area
+ * @return {Query} this
+ * @see $center http://docs.mongodb.org/manual/reference/operator/center/
+ * @see $centerSphere http://docs.mongodb.org/manual/reference/operator/centerSphere/
+ * @see $geoWithin http://docs.mongodb.org/manual/reference/operator/geoWithin/
+ * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing
+ * @api public
+ */
+
+/**
+ * _DEPRECATED_ Alias for [circle](#query_Query-circle)
+ *
+ * **Deprecated.** Use [circle](#query_Query-circle) instead.
+ *
+ * @deprecated
+ * @method center
+ * @memberOf Query
+ * @api public
+ */
+
+Query.prototype.center = Query.base.circle;
+
+/**
+ * _DEPRECATED_ Specifies a $centerSphere condition
+ *
+ * **Deprecated.** Use [circle](#query_Query-circle) instead.
+ *
+ * ####Example
+ *
+ * var area = { center: [50, 50], radius: 10 };
+ * query.where('loc').within().centerSphere(area);
+ *
+ * @deprecated
+ * @param {String} [path]
+ * @param {Object} val
+ * @return {Query} this
+ * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing
+ * @see $centerSphere http://docs.mongodb.org/manual/reference/operator/centerSphere/
+ * @api public
+ */
+
+Query.prototype.centerSphere = function() {
+ if (arguments[0] && arguments[0].constructor.name === 'Object') {
+ arguments[0].spherical = true;
+ }
+
+ if (arguments[1] && arguments[1].constructor.name === 'Object') {
+ arguments[1].spherical = true;
+ }
+
+ Query.base.circle.apply(this, arguments);
+};
+
+/**
+ * Determines if field selection has been made.
+ *
+ * @method selected
+ * @memberOf Query
+ * @return {Boolean}
+ * @api public
+ */
+
+/**
+ * Determines if inclusive field selection has been made.
+ *
+ * query.selectedInclusively() // false
+ * query.select('name')
+ * query.selectedInclusively() // true
+ *
+ * @method selectedInclusively
+ * @memberOf Query
+ * @return {Boolean}
+ * @api public
+ */
+
+/**
+ * Determines if exclusive field selection has been made.
+ *
+ * query.selectedExclusively() // false
+ * query.select('-name')
+ * query.selectedExclusively() // true
+ * query.selectedInclusively() // false
+ *
+ * @method selectedExclusively
+ * @memberOf Query
+ * @return {Boolean}
+ * @api public
+ */
+
+/*!
+ * Export
+ */
+
+module.exports = Query;
diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/querycursor.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/querycursor.js
new file mode 100644
index 0000000..da82a5b
--- /dev/null
+++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/querycursor.js
@@ -0,0 +1,314 @@
+/*!
+ * Module dependencies.
+ */
+
+var PromiseProvider = require('./promise_provider');
+var Readable = require('stream').Readable;
+var helpers = require('./queryhelpers');
+var util = require('util');
+
+/**
+ * A QueryCursor is a concurrency primitive for processing query results
+ * one document at a time. A QueryCursor fulfills the [Node.js streams3 API](https://strongloop.com/strongblog/whats-new-io-js-beta-streams3/),
+ * in addition to several other mechanisms for loading documents from MongoDB
+ * one at a time.
+ *
+ * Unless you're an advanced user, do **not** instantiate this class directly.
+ * Use [`Query#cursor()`](/docs/api.html#query_Query-cursor) instead.
+ *
+ * @param {Query} query
+ * @param {Object} options query options passed to `.find()`
+ * @inherits Readable
+ * @event `cursor`: Emitted when the cursor is created
+ * @event `error`: Emitted when an error occurred
+ * @event `data`: Emitted when the stream is flowing and the next doc is ready
+ * @event `end`: Emitted when the stream is exhausted
+ * @api public
+ */
+
+function QueryCursor(query, options) {
+ Readable.call(this, { objectMode: true });
+
+ this.cursor = null;
+ this.query = query;
+ this._transforms = options.transform ? [options.transform] : [];
+ var _this = this;
+ var model = query.model;
+ model.collection.find(query._conditions, options, function(err, cursor) {
+ if (_this._error) {
+ cursor.close(function() {});
+ _this.listeners('error').length > 0 && _this.emit('error', _this._error);
+ }
+ if (err) {
+ return _this.emit('error', err);
+ }
+ _this.cursor = cursor;
+ _this.emit('cursor', cursor);
+ });
+}
+
+util.inherits(QueryCursor, Readable);
+
+/*!
+ * Necessary to satisfy the Readable API
+ */
+
+QueryCursor.prototype._read = function() {
+ var _this = this;
+ _next(this, function(error, doc) {
+ if (error) {
+ return _this.emit('error', error);
+ }
+ if (!doc) {
+ _this.push(null);
+ return _this.cursor.close(function(error) {
+ if (error) {
+ return _this.emit('error', error);
+ }
+ _this.emit('close');
+ });
+ }
+ _this.push(doc);
+ });
+};
+
+/**
+ * Registers a transform function which subsequently maps documents retrieved
+ * via the streams interface or `.next()`
+ *
+ * ####Example
+ *
+ * // Map documents returned by `data` events
+ * Thing.
+ * find({ name: /^hello/ }).
+ * cursor().
+ * map(function (doc) {
+ * doc.foo = "bar";
+ * return doc;
+ * })
+ * on('data', function(doc) { console.log(doc.foo); });
+ *
+ * // Or map documents returned by `.next()`
+ * var cursor = Thing.find({ name: /^hello/ }).
+ * cursor().
+ * map(function (doc) {
+ * doc.foo = "bar";
+ * return doc;
+ * });
+ * cursor.next(function(error, doc) {
+ * console.log(doc.foo);
+ * });
+ *
+ * @param {Function} fn
+ * @return {QueryCursor}
+ * @api public
+ * @method map
+ */
+
+QueryCursor.prototype.map = function(fn) {
+ this._transforms.push(fn);
+ return this;
+};
+
+/*!
+ * Marks this cursor as errored
+ */
+
+QueryCursor.prototype._markError = function(error) {
+ this._error = error;
+ return this;
+};
+
+/**
+ * Marks this cursor as closed. Will stop streaming and subsequent calls to
+ * `next()` will error.
+ *
+ * @param {Function} callback
+ * @return {Promise}
+ * @api public
+ * @method close
+ * @emits close
+ * @see MongoDB driver cursor#close http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#close
+ */
+
+QueryCursor.prototype.close = function(callback) {
+ var Promise = PromiseProvider.get();
+ var _this = this;
+ return new Promise.ES6(function(resolve, reject) {
+ _this.cursor.close(function(error) {
+ if (error) {
+ callback && callback(error);
+ reject(error);
+ return _this.listeners('error').length > 0 &&
+ _this.emit('error', error);
+ }
+ _this.emit('close');
+ resolve();
+ callback && callback();
+ });
+ });
+};
+
+/**
+ * Get the next document from this cursor. Will return `null` when there are
+ * no documents left.
+ *
+ * @param {Function} callback
+ * @return {Promise}
+ * @api public
+ * @method next
+ */
+
+QueryCursor.prototype.next = function(callback) {
+ var Promise = PromiseProvider.get();
+ var _this = this;
+ return new Promise.ES6(function(resolve, reject) {
+ _next(_this, function(error, doc) {
+ if (error) {
+ callback && callback(error);
+ return reject(error);
+ }
+ callback && callback(null, doc);
+ resolve(doc);
+ });
+ });
+};
+
+/**
+ * Execute `fn` for every document in the cursor. If `fn` returns a promise,
+ * will wait for the promise to resolve before iterating on to the next one.
+ * Returns a promise that resolves when done.
+ *
+ * @param {Function} fn
+ * @param {Function} [callback] executed when all docs have been processed
+ * @return {Promise}
+ * @api public
+ * @method eachAsync
+ */
+
+QueryCursor.prototype.eachAsync = function(fn, callback) {
+ var Promise = PromiseProvider.get();
+ var _this = this;
+
+ var handleNextResult = function(doc, callback) {
+ var promise = fn(doc);
+ if (promise && typeof promise.then === 'function') {
+ promise.then(
+ function() { callback(null); },
+ function(error) { callback(error); });
+ } else {
+ callback(null);
+ }
+ };
+
+ var iterate = function(callback) {
+ return _next(_this, function(error, doc) {
+ if (error) {
+ return callback(error);
+ }
+ if (!doc) {
+ return callback(null);
+ }
+ handleNextResult(doc, function(error) {
+ if (error) {
+ return callback(error);
+ }
+ // Make sure to clear the stack re: gh-4697
+ setTimeout(function() {
+ iterate(callback);
+ }, 0);
+ });
+ });
+ };
+
+ return new Promise.ES6(function(resolve, reject) {
+ iterate(function(error) {
+ if (error) {
+ callback && callback(error);
+ return reject(error);
+ }
+ callback && callback(null);
+ return resolve();
+ });
+ });
+};
+
+/*!
+ * Get the next doc from the underlying cursor and mongooseify it
+ * (populate, etc.)
+ */
+
+function _next(ctx, cb) {
+ var callback = cb;
+ if (ctx._transforms.length) {
+ callback = function(err, doc) {
+ if (err || doc === null) return cb(err, doc);
+ cb(err, ctx._transforms.reduce(function(doc, fn) {
+ return fn(doc);
+ }, doc));
+ };
+ }
+
+ if (ctx._error) {
+ return process.nextTick(function() {
+ callback(ctx._error);
+ });
+ }
+
+ if (ctx.cursor) {
+ ctx.cursor.next(function(error, doc) {
+ if (error) {
+ return callback(error);
+ }
+ if (!doc) {
+ return callback(null, null);
+ }
+
+ var opts = ctx.query._mongooseOptions;
+ if (!opts.populate) {
+ return opts.lean === true ?
+ callback(null, doc) :
+ _create(ctx, doc, null, callback);
+ }
+
+ var pop = helpers.preparePopulationOptionsMQ(ctx.query,
+ ctx.query._mongooseOptions);
+ pop.forEach(function(option) {
+ delete option.model;
+ });
+ pop.__noPromise = true;
+ ctx.query.model.populate(doc, pop, function(err, doc) {
+ if (err) {
+ return callback(err);
+ }
+ return opts.lean === true ?
+ callback(null, doc) :
+ _create(ctx, doc, pop, callback);
+ });
+ });
+ } else {
+ ctx.once('cursor', function() {
+ _next(ctx, callback);
+ });
+ }
+}
+
+/*!
+ * Convert a raw doc into a full mongoose doc.
+ */
+
+function _create(ctx, doc, populatedIds, cb) {
+ var instance = helpers.createModel(ctx.query.model, doc, ctx.query._fields);
+ var opts = populatedIds ?
+ { populated: populatedIds } :
+ undefined;
+
+ instance.init(doc, opts, function(err) {
+ if (err) {
+ return cb(err);
+ }
+ cb(null, instance);
+ });
+}
+
+module.exports = QueryCursor;
diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/queryhelpers.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/queryhelpers.js
new file mode 100644
index 0000000..3e0b82d
--- /dev/null
+++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/queryhelpers.js
@@ -0,0 +1,78 @@
+
+/*!
+ * 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;
+}
diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/querystream.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/querystream.js
new file mode 100644
index 0000000..2918e25
--- /dev/null
+++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/querystream.js
@@ -0,0 +1,367 @@
+/* eslint no-empty: 1 */
+
+/*!
+ * 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 && typeof options.transform === 'function'
+ ? options.transform
+ : K;
+
+ // give time to hook up events
+ var _this = this;
+ process.nextTick(function() {
+ _this._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),
+ _this = this;
+
+ try {
+ query.cast(model);
+ } catch (err) {
+ return _this.destroy(err);
+ }
+
+ _this._fields = utils.clone(query._fields);
+ options.fields = query._castFields(_this._fields);
+
+ model.collection.find(query._conditions, options, function(err, cursor) {
+ if (err) {
+ return _this.destroy(err);
+ }
+ _this._cursor = cursor;
+ _this._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) {
+ this._running = false;
+ return this._running;
+ }
+
+ this._running = true;
+
+ if (this._buffer && this._buffer.length) {
+ var arg;
+ while (!this.paused && !this._destroyed && (arg = this._buffer.shift())) { // eslint-disable-line no-cond-assign
+ 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) {
+ this._running = false;
+ return this._running;
+ }
+
+ var _this = this;
+ _this._inline = T_INIT;
+
+ _this._cursor.nextObject(function cursorcb(err, doc) {
+ _this._onNextObject(err, doc);
+ });
+
+ // if onNextObject() was already called in this tick
+ // return ourselves to the trampoline.
+ if (T_CONT === this._inline) {
+ return true;
+ }
+ // 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]);
+ this._running = false;
+ return this._running;
+ }
+
+ 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 opts.lean === true ?
+ emit(this, doc) :
+ createAndEmit(this, null, doc);
+ }
+
+ var _this = this;
+ var pop = helpers.preparePopulationOptionsMQ(_this.query, _this.query._mongooseOptions);
+
+ // Hack to work around gh-3108
+ pop.forEach(function(option) {
+ delete option.model;
+ });
+
+ pop.__noPromise = true;
+ _this.query.model.populate(doc, pop, function(err, doc) {
+ if (err) {
+ return _this.destroy(err);
+ }
+ return opts.lean === true ?
+ emit(_this, doc) :
+ createAndEmit(_this, 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, which emits the close event. No more events will be emitted after the close event.
+ *
+ * @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;
diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/schema.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/schema.js
new file mode 100644
index 0000000..7e28f58
--- /dev/null
+++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/schema.js
@@ -0,0 +1,1768 @@
+/*!
+ * Module dependencies.
+ */
+
+var readPref = require('./drivers').ReadPreference;
+var EventEmitter = require('events').EventEmitter;
+var VirtualType = require('./virtualtype');
+var utils = require('./utils');
+var MongooseTypes;
+var Kareem = require('kareem');
+var each = require('async/each');
+var SchemaType = require('./schematype');
+
+var IS_KAREEM_HOOK = {
+ count: true,
+ find: true,
+ findOne: true,
+ findOneAndUpdate: true,
+ findOneAndRemove: true,
+ insertMany: true,
+ update: true
+};
+
+/**
+ * Schema constructor.
+ *
+ * ####Example:
+ *
+ * var child = new Schema({ name: String });
+ * var schema = new Schema({ name: String, age: Number, children: [child] });
+ * var Tree = mongoose.model('Tree', schema);
+ *
+ * // setting schema options
+ * new Schema({ name: String }, { _id: false, autoIndex: false })
+ *
+ * ####Options:
+ *
+ * - [autoIndex](/docs/guide.html#autoIndex): bool - defaults to null (which means use the connection's autoIndex option)
+ * - [bufferCommands](/docs/guide.html#bufferCommands): bool - defaults to true
+ * - [capped](/docs/guide.html#capped): bool - defaults to false
+ * - [collection](/docs/guide.html#collection): string - no default
+ * - [emitIndexErrors](/docs/guide.html#emitIndexErrors): bool - defaults to false.
+ * - [id](/docs/guide.html#id): bool - defaults to true
+ * - [_id](/docs/guide.html#_id): bool - defaults to true
+ * - `minimize`: bool - controls [document#toObject](#document_Document-toObject) behavior when called manually - defaults to true
+ * - [read](/docs/guide.html#read): string
+ * - [safe](/docs/guide.html#safe): bool - defaults to true.
+ * - [shardKey](/docs/guide.html#shardKey): bool - defaults to `null`
+ * - [strict](/docs/guide.html#strict): bool - defaults to true
+ * - [toJSON](/docs/guide.html#toJSON) - object - no default
+ * - [toObject](/docs/guide.html#toObject) - object - no default
+ * - [typeKey](/docs/guide.html#typeKey) - string - defaults to 'type'
+ * - [useNestedStrict](/docs/guide.html#useNestedStrict) - boolean - defaults to false
+ * - [validateBeforeSave](/docs/guide.html#validateBeforeSave) - bool - defaults to `true`
+ * - [versionKey](/docs/guide.html#versionKey): string - defaults to "__v"
+ *
+ * ####Note:
+ *
+ * _When nesting schemas, (`children` in the example above), always declare the child schema first before passing it into its parent._
+ *
+ * @param {Object} definition
+ * @param {Object} [options]
+ * @inherits NodeJS EventEmitter http://nodejs.org/api/events.html#events_class_events_eventemitter
+ * @event `init`: Emitted after the schema is compiled into a `Model`.
+ * @api public
+ */
+
+function Schema(obj, options) {
+ if (!(this instanceof Schema)) {
+ return new Schema(obj, options);
+ }
+
+ this.obj = obj;
+ this.paths = {};
+ this.subpaths = {};
+ this.virtuals = {};
+ this.singleNestedPaths = {};
+ this.nested = {};
+ this.inherits = {};
+ this.callQueue = [];
+ this._indexes = [];
+ this.methods = {};
+ this.statics = {};
+ this.tree = {};
+ this._requiredpaths = undefined;
+ this.discriminatorMapping = undefined;
+ this._indexedpaths = undefined;
+ this.query = {};
+ this.childSchemas = [];
+
+ this.s = {
+ hooks: new Kareem(),
+ kareemHooks: IS_KAREEM_HOOK
+ };
+
+ this.options = this.defaultOptions(options);
+
+ // build paths
+ if (obj) {
+ this.add(obj);
+ }
+
+ // check if _id's value is a subdocument (gh-2276)
+ var _idSubDoc = obj && obj._id && utils.isObject(obj._id);
+
+ // ensure the documents get an auto _id unless disabled
+ var auto_id = !this.paths['_id'] &&
+ (!this.options.noId && this.options._id) && !_idSubDoc;
+
+ if (auto_id) {
+ obj = {_id: {auto: true}};
+ obj._id[this.options.typeKey] = Schema.ObjectId;
+ this.add(obj);
+ }
+
+ // ensure the documents receive an id getter unless disabled
+ var autoid = !this.paths['id'] &&
+ (!this.options.noVirtualId && this.options.id);
+ if (autoid) {
+ this.virtual('id').get(idGetter);
+ }
+
+ for (var i = 0; i < this._defaultMiddleware.length; ++i) {
+ var m = this._defaultMiddleware[i];
+ this[m.kind](m.hook, !!m.isAsync, m.fn);
+ }
+
+ if (this.options.timestamps) {
+ this.setupTimestamp(this.options.timestamps);
+ }
+}
+
+/*!
+ * Returns this documents _id cast to a string.
+ */
+
+function idGetter() {
+ if (this.$__._id) {
+ return this.$__._id;
+ }
+
+ this.$__._id = this._id == null
+ ? null
+ : String(this._id);
+ return this.$__._id;
+}
+
+/*!
+ * Inherit from EventEmitter.
+ */
+Schema.prototype = Object.create(EventEmitter.prototype);
+Schema.prototype.constructor = Schema;
+Schema.prototype.instanceOfSchema = true;
+
+/**
+ * Default middleware attached to a schema. Cannot be changed.
+ *
+ * This field is used to make sure discriminators don't get multiple copies of
+ * built-in middleware. Declared as a constant because changing this at runtime
+ * may lead to instability with Model.prototype.discriminator().
+ *
+ * @api private
+ * @property _defaultMiddleware
+ */
+Object.defineProperty(Schema.prototype, '_defaultMiddleware', {
+ configurable: false,
+ enumerable: false,
+ writable: false,
+ value: [
+ {
+ kind: 'pre',
+ hook: 'save',
+ fn: function(next, options) {
+ var _this = this;
+ // Nested docs have their own presave
+ if (this.ownerDocument) {
+ return next();
+ }
+
+ var hasValidateBeforeSaveOption = options &&
+ (typeof options === 'object') &&
+ ('validateBeforeSave' in options);
+
+ var shouldValidate;
+ if (hasValidateBeforeSaveOption) {
+ shouldValidate = !!options.validateBeforeSave;
+ } else {
+ shouldValidate = this.schema.options.validateBeforeSave;
+ }
+
+ // Validate
+ if (shouldValidate) {
+ // HACK: use $__original_validate to avoid promises so bluebird doesn't
+ // complain
+ if (this.$__original_validate) {
+ this.$__original_validate({__noPromise: true}, function(error) {
+ return _this.schema.s.hooks.execPost('save:error', _this, [_this], { error: error }, function(error) {
+ next(error);
+ });
+ });
+ } else {
+ this.validate({__noPromise: true}, function(error) {
+ return _this.schema.s.hooks.execPost('save:error', _this, [ _this], { error: error }, function(error) {
+ next(error);
+ });
+ });
+ }
+ } else {
+ next();
+ }
+ }
+ },
+ {
+ kind: 'pre',
+ hook: 'save',
+ isAsync: true,
+ fn: function(next, done) {
+ var _this = this;
+ var subdocs = this.$__getAllSubdocs();
+
+ if (!subdocs.length || this.$__preSavingFromParent) {
+ done();
+ next();
+ return;
+ }
+
+ each(subdocs, function(subdoc, cb) {
+ subdoc.$__preSavingFromParent = true;
+ subdoc.save(function(err) {
+ cb(err);
+ });
+ }, function(error) {
+ for (var i = 0; i < subdocs.length; ++i) {
+ delete subdocs[i].$__preSavingFromParent;
+ }
+ if (error) {
+ return _this.schema.s.hooks.execPost('save:error', _this, [_this], { error: error }, function(error) {
+ done(error);
+ });
+ }
+ next();
+ done();
+ });
+ }
+ },
+ {
+ kind: 'pre',
+ hook: 'validate',
+ isAsync: true,
+ fn: function(next, done) {
+ // Hack to ensure that we always wrap validate() in a promise
+ next();
+ done();
+ }
+ },
+ {
+ kind: 'pre',
+ hook: 'remove',
+ isAsync: true,
+ fn: function(next, done) {
+ if (this.ownerDocument) {
+ done();
+ next();
+ return;
+ }
+
+ var subdocs = this.$__getAllSubdocs();
+
+ if (!subdocs.length || this.$__preSavingFromParent) {
+ done();
+ next();
+ return;
+ }
+
+ each(subdocs, function(subdoc, cb) {
+ subdoc.remove({ noop: true }, function(err) {
+ cb(err);
+ });
+ }, function(error) {
+ if (error) {
+ done(error);
+ return;
+ }
+ next();
+ done();
+ });
+ }
+ }
+ ]
+});
+
+
+/**
+ * The original object passed to the schema constructor
+ *
+ * ####Example:
+ *
+ * var schema = new Schema({ a: String }).add({ b: String });
+ * schema.obj; // { a: String }
+ *
+ * @api public
+ * @property obj
+ */
+
+Schema.prototype.obj;
+
+/**
+ * Schema as flat paths
+ *
+ * ####Example:
+ * {
+ * '_id' : SchemaType,
+ * , 'nested.key' : SchemaType,
+ * }
+ *
+ * @api private
+ * @property paths
+ */
+
+Schema.prototype.paths;
+
+/**
+ * Schema as a tree
+ *
+ * ####Example:
+ * {
+ * '_id' : ObjectId
+ * , 'nested' : {
+ * 'key' : String
+ * }
+ * }
+ *
+ * @api private
+ * @property tree
+ */
+
+Schema.prototype.tree;
+
+/**
+ * Returns default options for this schema, merged with `options`.
+ *
+ * @param {Object} options
+ * @return {Object}
+ * @api private
+ */
+
+Schema.prototype.defaultOptions = function(options) {
+ if (options && options.safe === false) {
+ options.safe = {w: 0};
+ }
+
+ if (options && options.safe && options.safe.w === 0) {
+ // if you turn off safe writes, then versioning goes off as well
+ options.versionKey = false;
+ }
+
+ options = utils.options({
+ strict: true,
+ bufferCommands: true,
+ capped: false, // { size, max, autoIndexId }
+ versionKey: '__v',
+ discriminatorKey: '__t',
+ minimize: true,
+ autoIndex: null,
+ shardKey: null,
+ read: null,
+ validateBeforeSave: true,
+ // the following are only applied at construction time
+ noId: false, // deprecated, use { _id: false }
+ _id: true,
+ noVirtualId: false, // deprecated, use { id: false }
+ id: true,
+ typeKey: 'type',
+ retainKeyOrder: false
+ }, options);
+
+ if (options.read) {
+ options.read = readPref(options.read);
+ }
+
+ return options;
+};
+
+/**
+ * Adds key path / schema type pairs to this schema.
+ *
+ * ####Example:
+ *
+ * var ToySchema = new Schema;
+ * ToySchema.add({ name: 'string', color: 'string', price: 'number' });
+ *
+ * @param {Object} obj
+ * @param {String} prefix
+ * @api public
+ */
+
+Schema.prototype.add = function add(obj, prefix) {
+ prefix = prefix || '';
+ var keys = Object.keys(obj);
+
+ for (var i = 0; i < keys.length; ++i) {
+ var key = keys[i];
+
+ if (obj[key] == null) {
+ throw new TypeError('Invalid value for schema path `' + prefix + key + '`');
+ }
+
+ if (Array.isArray(obj[key]) && obj[key].length === 1 && obj[key][0] == null) {
+ throw new TypeError('Invalid value for schema Array path `' + prefix + key + '`');
+ }
+
+ if (utils.isObject(obj[key]) &&
+ (!obj[key].constructor || utils.getFunctionName(obj[key].constructor) === 'Object') &&
+ (!obj[key][this.options.typeKey] || (this.options.typeKey === 'type' && obj[key].type.type))) {
+ if (Object.keys(obj[key]).length) {
+ // nested object { last: { name: String }}
+ this.nested[prefix + key] = true;
+ this.add(obj[key], prefix + key + '.');
+ } else {
+ if (prefix) {
+ this.nested[prefix.substr(0, prefix.length - 1)] = true;
+ }
+ this.path(prefix + key, obj[key]); // mixed type
+ }
+ } else {
+ if (prefix) {
+ this.nested[prefix.substr(0, prefix.length - 1)] = true;
+ }
+ this.path(prefix + key, obj[key]);
+ }
+ }
+};
+
+/**
+ * Reserved document keys.
+ *
+ * Keys in this object are names that are rejected in schema declarations b/c they conflict with mongoose functionality. Using these key name will throw an error.
+ *
+ * on, emit, _events, db, get, set, init, isNew, errors, schema, options, modelName, collection, _pres, _posts, toObject
+ *
+ * _NOTE:_ Use of these terms as method names is permitted, but play at your own risk, as they may be existing mongoose document methods you are stomping on.
+ *
+ * var schema = new Schema(..);
+ * schema.methods.init = function () {} // potentially breaking
+ */
+
+Schema.reserved = Object.create(null);
+var reserved = Schema.reserved;
+// Core object
+reserved['prototype'] =
+// EventEmitter
+reserved.emit =
+reserved.on =
+reserved.once =
+reserved.listeners =
+reserved.removeListener =
+// document properties and functions
+reserved.collection =
+reserved.db =
+reserved.errors =
+reserved.init =
+reserved.isModified =
+reserved.isNew =
+reserved.get =
+reserved.modelName =
+reserved.save =
+reserved.schema =
+reserved.set =
+reserved.toObject =
+reserved.validate =
+// hooks.js
+reserved._pres = reserved._posts = 1;
+
+/*!
+ * Document keys to print warnings for
+ */
+
+var warnings = {};
+warnings.increment = '`increment` should not be used as a schema path name ' +
+ 'unless you have disabled versioning.';
+
+/**
+ * Gets/sets schema paths.
+ *
+ * Sets a path (if arity 2)
+ * Gets a path (if arity 1)
+ *
+ * ####Example
+ *
+ * schema.path('name') // returns a SchemaType
+ * schema.path('name', Number) // changes the schemaType of `name` to Number
+ *
+ * @param {String} path
+ * @param {Object} constructor
+ * @api public
+ */
+
+Schema.prototype.path = function(path, obj) {
+ if (obj === undefined) {
+ if (this.paths[path]) {
+ return this.paths[path];
+ }
+ if (this.subpaths[path]) {
+ return this.subpaths[path];
+ }
+ if (this.singleNestedPaths[path]) {
+ return this.singleNestedPaths[path];
+ }
+
+ // subpaths?
+ return /\.\d+\.?.*$/.test(path)
+ ? getPositionalPath(this, path)
+ : undefined;
+ }
+
+ // some path names conflict with document methods
+ if (reserved[path]) {
+ throw new Error('`' + path + '` may not be used as a schema pathname');
+ }
+
+ if (warnings[path]) {
+ console.log('WARN: ' + warnings[path]);
+ }
+
+ // update the tree
+ var subpaths = path.split(/\./),
+ last = subpaths.pop(),
+ branch = this.tree;
+
+ subpaths.forEach(function(sub, i) {
+ if (!branch[sub]) {
+ branch[sub] = {};
+ }
+ if (typeof branch[sub] !== 'object') {
+ var msg = 'Cannot set nested path `' + path + '`. '
+ + 'Parent path `'
+ + subpaths.slice(0, i).concat([sub]).join('.')
+ + '` already set to type ' + branch[sub].name
+ + '.';
+ throw new Error(msg);
+ }
+ branch = branch[sub];
+ });
+
+ branch[last] = utils.clone(obj);
+
+ this.paths[path] = Schema.interpretAsType(path, obj, this.options);
+
+ if (this.paths[path].$isSingleNested) {
+ for (var key in this.paths[path].schema.paths) {
+ this.singleNestedPaths[path + '.' + key] =
+ this.paths[path].schema.paths[key];
+ }
+ for (key in this.paths[path].schema.singleNestedPaths) {
+ this.singleNestedPaths[path + '.' + key] =
+ this.paths[path].schema.singleNestedPaths[key];
+ }
+
+ this.childSchemas.push(this.paths[path].schema);
+ } else if (this.paths[path].$isMongooseDocumentArray) {
+ this.childSchemas.push(this.paths[path].schema);
+ }
+ return this;
+};
+
+/**
+ * Converts type arguments into Mongoose Types.
+ *
+ * @param {String} path
+ * @param {Object} obj constructor
+ * @api private
+ */
+
+Schema.interpretAsType = function(path, obj, options) {
+ if (obj.constructor) {
+ var constructorName = utils.getFunctionName(obj.constructor);
+ if (constructorName !== 'Object') {
+ var oldObj = obj;
+ obj = {};
+ obj[options.typeKey] = oldObj;
+ }
+ }
+
+ // Get the type making sure to allow keys named "type"
+ // and default to mixed if not specified.
+ // { type: { type: String, default: 'freshcut' } }
+ var type = obj[options.typeKey] && (options.typeKey !== 'type' || !obj.type.type)
+ ? obj[options.typeKey]
+ : {};
+
+ if (utils.getFunctionName(type.constructor) === 'Object' || type === 'mixed') {
+ return new MongooseTypes.Mixed(path, obj);
+ }
+
+ if (Array.isArray(type) || Array === type || type === 'array') {
+ // if it was specified through { type } look for `cast`
+ var cast = (Array === type || type === 'array')
+ ? obj.cast
+ : type[0];
+
+ if (cast && cast.instanceOfSchema) {
+ return new MongooseTypes.DocumentArray(path, cast, obj);
+ }
+
+ if (Array.isArray(cast)) {
+ return new MongooseTypes.Array(path, Schema.interpretAsType(path, cast, options), obj);
+ }
+
+ if (typeof cast === 'string') {
+ cast = MongooseTypes[cast.charAt(0).toUpperCase() + cast.substring(1)];
+ } else if (cast && (!cast[options.typeKey] || (options.typeKey === 'type' && cast.type.type))
+ && utils.getFunctionName(cast.constructor) === 'Object') {
+ if (Object.keys(cast).length) {
+ // The `minimize` and `typeKey` options propagate to child schemas
+ // declared inline, like `{ arr: [{ val: { $type: String } }] }`.
+ // See gh-3560
+ var childSchemaOptions = {minimize: options.minimize};
+ if (options.typeKey) {
+ childSchemaOptions.typeKey = options.typeKey;
+ }
+ var childSchema = new Schema(cast, childSchemaOptions);
+ childSchema.$implicitlyCreated = true;
+ return new MongooseTypes.DocumentArray(path, childSchema, obj);
+ } else {
+ // Special case: empty object becomes mixed
+ return new MongooseTypes.Array(path, MongooseTypes.Mixed, obj);
+ }
+ }
+
+ if (cast) {
+ type = cast[options.typeKey] && (options.typeKey !== 'type' || !cast.type.type)
+ ? cast[options.typeKey]
+ : cast;
+
+ name = typeof type === 'string'
+ ? type
+ : type.schemaName || utils.getFunctionName(type);
+
+ if (!(name in MongooseTypes)) {
+ throw new TypeError('Undefined type `' + name + '` at array `' + path +
+ '`');
+ }
+ }
+
+ return new MongooseTypes.Array(path, cast || MongooseTypes.Mixed, obj, options);
+ }
+
+ if (type && type.instanceOfSchema) {
+ return new MongooseTypes.Embedded(type, path, obj);
+ }
+
+ var name;
+ if (Buffer.isBuffer(type)) {
+ name = 'Buffer';
+ } else {
+ name = typeof type === 'string'
+ ? type
+ // If not string, `type` is a function. Outside of IE, function.name
+ // gives you the function name. In IE, you need to compute it
+ : type.schemaName || utils.getFunctionName(type);
+ }
+
+ if (name) {
+ name = name.charAt(0).toUpperCase() + name.substring(1);
+ }
+
+ if (undefined == MongooseTypes[name]) {
+ throw new TypeError('Undefined type `' + name + '` at `' + path +
+ '`\n Did you try nesting Schemas? ' +
+ 'You can only nest using refs or arrays.');
+ }
+
+ return new MongooseTypes[name](path, obj);
+};
+
+/**
+ * Iterates the schemas paths similar to Array#forEach.
+ *
+ * The callback is passed the pathname and schemaType as arguments on each iteration.
+ *
+ * @param {Function} fn callback function
+ * @return {Schema} this
+ * @api public
+ */
+
+Schema.prototype.eachPath = function(fn) {
+ var keys = Object.keys(this.paths),
+ len = keys.length;
+
+ for (var i = 0; i < len; ++i) {
+ fn(keys[i], this.paths[keys[i]]);
+ }
+
+ return this;
+};
+
+/**
+ * Returns an Array of path strings that are required by this schema.
+ *
+ * @api public
+ * @param {Boolean} invalidate refresh the cache
+ * @return {Array}
+ */
+
+Schema.prototype.requiredPaths = function requiredPaths(invalidate) {
+ if (this._requiredpaths && !invalidate) {
+ return this._requiredpaths;
+ }
+
+ var paths = Object.keys(this.paths),
+ i = paths.length,
+ ret = [];
+
+ while (i--) {
+ var path = paths[i];
+ if (this.paths[path].isRequired) {
+ ret.push(path);
+ }
+ }
+ this._requiredpaths = ret;
+ return this._requiredpaths;
+};
+
+/**
+ * Returns indexes from fields and schema-level indexes (cached).
+ *
+ * @api private
+ * @return {Array}
+ */
+
+Schema.prototype.indexedPaths = function indexedPaths() {
+ if (this._indexedpaths) {
+ return this._indexedpaths;
+ }
+ this._indexedpaths = this.indexes();
+ return this._indexedpaths;
+};
+
+/**
+ * Returns the pathType of `path` for this schema.
+ *
+ * Given a path, returns whether it is a real, virtual, nested, or ad-hoc/undefined path.
+ *
+ * @param {String} path
+ * @return {String}
+ * @api public
+ */
+
+Schema.prototype.pathType = function(path) {
+ if (path in this.paths) {
+ return 'real';
+ }
+ if (path in this.virtuals) {
+ return 'virtual';
+ }
+ if (path in this.nested) {
+ return 'nested';
+ }
+ if (path in this.subpaths) {
+ return 'real';
+ }
+ if (path in this.singleNestedPaths) {
+ return 'real';
+ }
+
+ if (/\.\d+\.|\.\d+$/.test(path)) {
+ return getPositionalPathType(this, path);
+ }
+ return 'adhocOrUndefined';
+};
+
+/**
+ * Returns true iff this path is a child of a mixed schema.
+ *
+ * @param {String} path
+ * @return {Boolean}
+ * @api private
+ */
+
+Schema.prototype.hasMixedParent = function(path) {
+ var subpaths = path.split(/\./g);
+ path = '';
+ for (var i = 0; i < subpaths.length; ++i) {
+ path = i > 0 ? path + '.' + subpaths[i] : subpaths[i];
+ if (path in this.paths &&
+ this.paths[path] instanceof MongooseTypes.Mixed) {
+ return true;
+ }
+ }
+
+ return false;
+};
+
+/**
+ * Setup updatedAt and createdAt timestamps to documents if enabled
+ *
+ * @param {Boolean|Object} timestamps timestamps options
+ * @api private
+ */
+Schema.prototype.setupTimestamp = function(timestamps) {
+ if (timestamps) {
+ var createdAt = timestamps.createdAt || 'createdAt';
+ var updatedAt = timestamps.updatedAt || 'updatedAt';
+ var schemaAdditions = {};
+
+ schemaAdditions[updatedAt] = Date;
+
+ if (!this.paths[createdAt]) {
+ schemaAdditions[createdAt] = Date;
+ }
+
+ this.add(schemaAdditions);
+
+ this.pre('save', function(next) {
+ var defaultTimestamp = new Date();
+ var auto_id = this._id && this._id.auto;
+
+ if (!this[createdAt] && this.isSelected(createdAt)) {
+ this[createdAt] = auto_id ? this._id.getTimestamp() : defaultTimestamp;
+ }
+
+ if (this.isNew || this.isModified()) {
+ this[updatedAt] = this.isNew ? this[createdAt] : defaultTimestamp;
+ }
+
+ next();
+ });
+
+ var genUpdates = function(overwrite) {
+ var now = new Date();
+ var updates = {};
+ if (overwrite) {
+ updates[updatedAt] = now;
+ updates[createdAt] = now;
+ return updates;
+ }
+ updates = { $set: {}, $setOnInsert: {} };
+ updates.$set[updatedAt] = now;
+ updates.$setOnInsert[createdAt] = now;
+
+ return updates;
+ };
+
+ this.methods.initializeTimestamps = function() {
+ if (!this[createdAt]) {
+ this[createdAt] = new Date();
+ }
+ if (!this[updatedAt]) {
+ this[updatedAt] = new Date();
+ }
+ return this;
+ };
+
+ this.pre('findOneAndUpdate', function(next) {
+ var overwrite = this.options.overwrite;
+ this.findOneAndUpdate({}, genUpdates(overwrite), { overwrite: overwrite });
+ applyTimestampsToChildren(this);
+ next();
+ });
+
+ this.pre('update', function(next) {
+ var overwrite = this.options.overwrite;
+ this.update({}, genUpdates(overwrite), { overwrite: overwrite });
+ applyTimestampsToChildren(this);
+ next();
+ });
+ }
+};
+
+/*!
+ * ignore
+ */
+
+function applyTimestampsToChildren(query) {
+ var now = new Date();
+ var update = query.getUpdate();
+ var keys = Object.keys(update);
+ var key;
+ var schema = query.model.schema;
+ var len;
+ var createdAt;
+ var updatedAt;
+ var timestamps;
+ var path;
+
+ var hasDollarKey = keys.length && keys[0].charAt(0) === '$';
+
+ if (hasDollarKey) {
+ if (update.$push) {
+ for (key in update.$push) {
+ var $path = schema.path(key);
+ if (update.$push[key] &&
+ $path &&
+ $path.$isMongooseDocumentArray &&
+ $path.schema.options.timestamps) {
+ timestamps = $path.schema.options.timestamps;
+ createdAt = timestamps.createdAt || 'createdAt';
+ updatedAt = timestamps.updatedAt || 'updatedAt';
+ update.$push[key][updatedAt] = now;
+ update.$push[key][createdAt] = now;
+ }
+ }
+ }
+ if (update.$set) {
+ for (key in update.$set) {
+ path = schema.path(key);
+ if (!path) {
+ continue;
+ }
+ if (Array.isArray(update.$set[key]) && path.$isMongooseDocumentArray) {
+ len = update.$set[key].length;
+ timestamps = schema.path(key).schema.options.timestamps;
+ if (timestamps) {
+ createdAt = timestamps.createdAt || 'createdAt';
+ updatedAt = timestamps.updatedAt || 'updatedAt';
+ for (var i = 0; i < len; ++i) {
+ update.$set[key][i][updatedAt] = now;
+ update.$set[key][i][createdAt] = now;
+ }
+ }
+ } else if (update.$set[key] && path.$isSingleNested) {
+ timestamps = schema.path(key).schema.options.timestamps;
+ if (timestamps) {
+ createdAt = timestamps.createdAt || 'createdAt';
+ updatedAt = timestamps.updatedAt || 'updatedAt';
+ update.$set[key][updatedAt] = now;
+ update.$set[key][createdAt] = now;
+ }
+ }
+ }
+ }
+ }
+}
+
+/*!
+ * ignore
+ */
+
+function getPositionalPathType(self, path) {
+ var subpaths = path.split(/\.(\d+)\.|\.(\d+)$/).filter(Boolean);
+ if (subpaths.length < 2) {
+ return self.paths[subpaths[0]];
+ }
+
+ var val = self.path(subpaths[0]);
+ var isNested = false;
+ if (!val) {
+ return val;
+ }
+
+ var last = subpaths.length - 1,
+ subpath,
+ i = 1;
+
+ for (; i < subpaths.length; ++i) {
+ isNested = false;
+ subpath = subpaths[i];
+
+ if (i === last && val && !/\D/.test(subpath)) {
+ if (val.$isMongooseDocumentArray) {
+ var oldVal = val;
+ val = new SchemaType(subpath);
+ val.cast = function(value, doc, init) {
+ return oldVal.cast(value, doc, init)[0];
+ };
+ val.caster = oldVal.caster;
+ val.schema = oldVal.schema;
+ } else if (val instanceof MongooseTypes.Array) {
+ // StringSchema, NumberSchema, etc
+ val = val.caster;
+ } else {
+ val = undefined;
+ }
+ break;
+ }
+
+ // ignore if its just a position segment: path.0.subpath
+ if (!/\D/.test(subpath)) {
+ continue;
+ }
+
+ if (!(val && val.schema)) {
+ val = undefined;
+ break;
+ }
+
+ var type = val.schema.pathType(subpath);
+ isNested = (type === 'nested');
+ val = val.schema.path(subpath);
+ }
+
+ self.subpaths[path] = val;
+ if (val) {
+ return 'real';
+ }
+ if (isNested) {
+ return 'nested';
+ }
+ return 'adhocOrUndefined';
+}
+
+
+/*!
+ * ignore
+ */
+
+function getPositionalPath(self, path) {
+ getPositionalPathType(self, path);
+ return self.subpaths[path];
+}
+
+/**
+ * Adds a method call to the queue.
+ *
+ * @param {String} name name of the document method to call later
+ * @param {Array} args arguments to pass to the method
+ * @api public
+ */
+
+Schema.prototype.queue = function(name, args) {
+ this.callQueue.push([name, args]);
+ return this;
+};
+
+/**
+ * Defines a pre hook for the document.
+ *
+ * ####Example
+ *
+ * var toySchema = new Schema(..);
+ *
+ * toySchema.pre('save', function (next) {
+ * if (!this.created) this.created = new Date;
+ * next();
+ * })
+ *
+ * toySchema.pre('validate', function (next) {
+ * if (this.name !== 'Woody') this.name = 'Woody';
+ * next();
+ * })
+ *
+ * @param {String} method
+ * @param {Function} callback
+ * @see hooks.js https://github.com/bnoguchi/hooks-js/tree/31ec571cef0332e21121ee7157e0cf9728572cc3
+ * @api public
+ */
+
+Schema.prototype.pre = function() {
+ var name = arguments[0];
+ if (IS_KAREEM_HOOK[name]) {
+ this.s.hooks.pre.apply(this.s.hooks, arguments);
+ return this;
+ }
+ return this.queue('pre', arguments);
+};
+
+/**
+ * Defines a post hook for the document
+ *
+ * var schema = new Schema(..);
+ * schema.post('save', function (doc) {
+ * console.log('this fired after a document was saved');
+ * });
+ *
+ * shema.post('find', function(docs) {
+ * console.log('this fired after you run a find query');
+ * });
+ *
+ * var Model = mongoose.model('Model', schema);
+ *
+ * var m = new Model(..);
+ * m.save(function(err) {
+ * console.log('this fires after the `post` hook');
+ * });
+ *
+ * m.find(function(err, docs) {
+ * console.log('this fires after the post find hook');
+ * });
+ *
+ * @param {String} method name of the method to hook
+ * @param {Function} fn callback
+ * @see middleware http://mongoosejs.com/docs/middleware.html
+ * @see hooks.js https://www.npmjs.com/package/hooks-fixed
+ * @see kareem http://npmjs.org/package/kareem
+ * @api public
+ */
+
+Schema.prototype.post = function(method, fn) {
+ if (IS_KAREEM_HOOK[method]) {
+ this.s.hooks.post.apply(this.s.hooks, arguments);
+ return this;
+ }
+ // assuming that all callbacks with arity < 2 are synchronous post hooks
+ if (fn.length < 2) {
+ return this.queue('on', [arguments[0], function(doc) {
+ return fn.call(doc, doc);
+ }]);
+ }
+
+ if (fn.length === 3) {
+ this.s.hooks.post(method + ':error', fn);
+ return this;
+ }
+
+ return this.queue('post', [arguments[0], function(next) {
+ // wrap original function so that the callback goes last,
+ // for compatibility with old code that is using synchronous post hooks
+ var _this = this;
+ var args = Array.prototype.slice.call(arguments, 1);
+ fn.call(this, this, function(err) {
+ return next.apply(_this, [err].concat(args));
+ });
+ }]);
+};
+
+/**
+ * Registers a plugin for this schema.
+ *
+ * @param {Function} plugin callback
+ * @param {Object} [opts]
+ * @see plugins
+ * @api public
+ */
+
+Schema.prototype.plugin = function(fn, opts) {
+ fn(this, opts);
+ return this;
+};
+
+/**
+ * Adds an instance method to documents constructed from Models compiled from this schema.
+ *
+ * ####Example
+ *
+ * var schema = kittySchema = new Schema(..);
+ *
+ * schema.method('meow', function () {
+ * console.log('meeeeeoooooooooooow');
+ * })
+ *
+ * var Kitty = mongoose.model('Kitty', schema);
+ *
+ * var fizz = new Kitty;
+ * fizz.meow(); // meeeeeooooooooooooow
+ *
+ * If a hash of name/fn pairs is passed as the only argument, each name/fn pair will be added as methods.
+ *
+ * schema.method({
+ * purr: function () {}
+ * , scratch: function () {}
+ * });
+ *
+ * // later
+ * fizz.purr();
+ * fizz.scratch();
+ *
+ * @param {String|Object} method name
+ * @param {Function} [fn]
+ * @api public
+ */
+
+Schema.prototype.method = function(name, fn) {
+ if (typeof name !== 'string') {
+ for (var i in name) {
+ this.methods[i] = name[i];
+ }
+ } else {
+ this.methods[name] = fn;
+ }
+ return this;
+};
+
+/**
+ * Adds static "class" methods to Models compiled from this schema.
+ *
+ * ####Example
+ *
+ * var schema = new Schema(..);
+ * schema.static('findByName', function (name, callback) {
+ * return this.find({ name: name }, callback);
+ * });
+ *
+ * var Drink = mongoose.model('Drink', schema);
+ * Drink.findByName('sanpellegrino', function (err, drinks) {
+ * //
+ * });
+ *
+ * If a hash of name/fn pairs is passed as the only argument, each name/fn pair will be added as statics.
+ *
+ * @param {String|Object} name
+ * @param {Function} [fn]
+ * @api public
+ */
+
+Schema.prototype.static = function(name, fn) {
+ if (typeof name !== 'string') {
+ for (var i in name) {
+ this.statics[i] = name[i];
+ }
+ } else {
+ this.statics[name] = fn;
+ }
+ return this;
+};
+
+/**
+ * Defines an index (most likely compound) for this schema.
+ *
+ * ####Example
+ *
+ * schema.index({ first: 1, last: -1 })
+ *
+ * @param {Object} fields
+ * @param {Object} [options] Options to pass to [MongoDB driver's `createIndex()` function](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#createIndex)
+ * @param {String} [options.expires=null] Mongoose-specific syntactic sugar, uses [ms](https://www.npmjs.com/package/ms) to convert `expires` option into seconds for the `expireAfterSeconds` in the above link.
+ * @api public
+ */
+
+Schema.prototype.index = function(fields, options) {
+ options || (options = {});
+
+ if (options.expires) {
+ utils.expires(options);
+ }
+
+ this._indexes.push([fields, options]);
+ return this;
+};
+
+/**
+ * Sets/gets a schema option.
+ *
+ * ####Example
+ *
+ * schema.set('strict'); // 'true' by default
+ * schema.set('strict', false); // Sets 'strict' to false
+ * schema.set('strict'); // 'false'
+ *
+ * @param {String} key option name
+ * @param {Object} [value] if not passed, the current option value is returned
+ * @see Schema ./
+ * @api public
+ */
+
+Schema.prototype.set = function(key, value, _tags) {
+ if (arguments.length === 1) {
+ return this.options[key];
+ }
+
+ switch (key) {
+ case 'read':
+ this.options[key] = readPref(value, _tags);
+ break;
+ case 'safe':
+ this.options[key] = value === false
+ ? {w: 0}
+ : value;
+ break;
+ case 'timestamps':
+ this.setupTimestamp(value);
+ this.options[key] = value;
+ break;
+ default:
+ this.options[key] = value;
+ }
+
+ return this;
+};
+
+/**
+ * Gets a schema option.
+ *
+ * @param {String} key option name
+ * @api public
+ */
+
+Schema.prototype.get = function(key) {
+ return this.options[key];
+};
+
+/**
+ * The allowed index types
+ *
+ * @static indexTypes
+ * @receiver Schema
+ * @api public
+ */
+
+var indexTypes = '2d 2dsphere hashed text'.split(' ');
+
+Object.defineProperty(Schema, 'indexTypes', {
+ get: function() {
+ return indexTypes;
+ },
+ set: function() {
+ throw new Error('Cannot overwrite Schema.indexTypes');
+ }
+});
+
+/**
+ * Compiles indexes from fields and schema-level indexes
+ *
+ * @api public
+ */
+
+Schema.prototype.indexes = function() {
+ 'use strict';
+
+ var indexes = [];
+ var seenPrefix = {};
+
+ var collectIndexes = function(schema, prefix) {
+ if (seenPrefix[prefix]) {
+ return;
+ }
+ seenPrefix[prefix] = true;
+
+ prefix = prefix || '';
+ var key, path, index, field, isObject, options, type;
+ var keys = Object.keys(schema.paths);
+
+ for (var i = 0; i < keys.length; ++i) {
+ key = keys[i];
+ path = schema.paths[key];
+
+ if ((path instanceof MongooseTypes.DocumentArray) || path.$isSingleNested) {
+ collectIndexes(path.schema, key + '.');
+ } else {
+ index = path._index;
+
+ if (index !== false && index !== null && index !== undefined) {
+ field = {};
+ isObject = utils.isObject(index);
+ options = isObject ? index : {};
+ type = typeof index === 'string' ? index :
+ isObject ? index.type :
+ false;
+
+ if (type && ~Schema.indexTypes.indexOf(type)) {
+ field[prefix + key] = type;
+ } else if (options.text) {
+ field[prefix + key] = 'text';
+ delete options.text;
+ } else {
+ field[prefix + key] = 1;
+ }
+
+ delete options.type;
+ if (!('background' in options)) {
+ options.background = true;
+ }
+
+ indexes.push([field, options]);
+ }
+ }
+ }
+
+ if (prefix) {
+ fixSubIndexPaths(schema, prefix);
+ } else {
+ schema._indexes.forEach(function(index) {
+ if (!('background' in index[1])) {
+ index[1].background = true;
+ }
+ });
+ indexes = indexes.concat(schema._indexes);
+ }
+ };
+
+ collectIndexes(this);
+ return indexes;
+
+ /*!
+ * Checks for indexes added to subdocs using Schema.index().
+ * These indexes need their paths prefixed properly.
+ *
+ * schema._indexes = [ [indexObj, options], [indexObj, options] ..]
+ */
+
+ function fixSubIndexPaths(schema, prefix) {
+ var subindexes = schema._indexes,
+ len = subindexes.length,
+ indexObj,
+ newindex,
+ klen,
+ keys,
+ key,
+ i = 0,
+ j;
+
+ for (i = 0; i < len; ++i) {
+ indexObj = subindexes[i][0];
+ keys = Object.keys(indexObj);
+ klen = keys.length;
+ newindex = {};
+
+ // use forward iteration, order matters
+ for (j = 0; j < klen; ++j) {
+ key = keys[j];
+ newindex[prefix + key] = indexObj[key];
+ }
+
+ indexes.push([newindex, subindexes[i][1]]);
+ }
+ }
+};
+
+/**
+ * Creates a virtual type with the given name.
+ *
+ * @param {String} name
+ * @param {Object} [options]
+ * @return {VirtualType}
+ */
+
+Schema.prototype.virtual = function(name, options) {
+ if (options && options.ref) {
+ if (!options.localField) {
+ throw new Error('Reference virtuals require `localField` option');
+ }
+
+ if (!options.foreignField) {
+ throw new Error('Reference virtuals require `foreignField` option');
+ }
+
+ this.pre('init', function(next, obj) {
+ if (name in obj) {
+ if (!this.$$populatedVirtuals) {
+ this.$$populatedVirtuals = {};
+ }
+
+ if (options.justOne) {
+ this.$$populatedVirtuals[name] = Array.isArray(obj[name]) ?
+ obj[name][0] :
+ obj[name];
+ } else {
+ this.$$populatedVirtuals[name] = Array.isArray(obj[name]) ?
+ obj[name] :
+ obj[name] == null ? [] : [obj[name]];
+ }
+
+ delete obj[name];
+ }
+ if (this.ownerDocument) {
+ next();
+ return obj;
+ } else {
+ next();
+ }
+ });
+
+ var virtual = this.virtual(name);
+ virtual.options = options;
+ return virtual.
+ get(function() {
+ if (!this.$$populatedVirtuals) {
+ this.$$populatedVirtuals = {};
+ }
+ if (name in this.$$populatedVirtuals) {
+ return this.$$populatedVirtuals[name];
+ }
+ return null;
+ }).
+ set(function(v) {
+ if (!this.$$populatedVirtuals) {
+ this.$$populatedVirtuals = {};
+ }
+ this.$$populatedVirtuals[name] = v;
+ });
+ }
+
+ var virtuals = this.virtuals;
+ var parts = name.split('.');
+
+ if (this.pathType(name) === 'real') {
+ throw new Error('Virtual path "' + name + '"' +
+ ' conflicts with a real path in the schema');
+ }
+
+ virtuals[name] = parts.reduce(function(mem, part, i) {
+ mem[part] || (mem[part] = (i === parts.length - 1)
+ ? new VirtualType(options, name)
+ : {});
+ return mem[part];
+ }, this.tree);
+
+ return virtuals[name];
+};
+
+/*!
+ * ignore
+ */
+
+Schema.prototype._getVirtual = function(name) {
+ return _getVirtual(this, name);
+};
+
+/*!
+ * ignore
+ */
+
+function _getVirtual(schema, name) {
+ var parts = name.split('.');
+ var cur = '';
+ var nestedSchemaPath = '';
+ for (var i = 0; i < parts.length; ++i) {
+ cur += (cur.length > 0 ? '.' : '') + parts[i];
+ if (schema.virtuals[cur]) {
+ if (i === parts.length - 1) {
+ schema.virtuals[cur].$nestedSchemaPath = nestedSchemaPath;
+ return schema.virtuals[cur];
+ }
+ continue;
+ } else if (schema.paths[cur] && schema.paths[cur].schema) {
+ schema = schema.paths[cur].schema;
+ nestedSchemaPath += (nestedSchemaPath.length > 0 ? '.' : '') + cur;
+ cur = '';
+ } else {
+ return null;
+ }
+ }
+}
+
+/**
+ * Returns the virtual type with the given `name`.
+ *
+ * @param {String} name
+ * @return {VirtualType}
+ */
+
+Schema.prototype.virtualpath = function(name) {
+ return this.virtuals[name];
+};
+
+/**
+ * Removes the given `path` (or [`paths`]).
+ *
+ * @param {String|Array} path
+ *
+ * @api public
+ */
+Schema.prototype.remove = function(path) {
+ if (typeof path === 'string') {
+ path = [path];
+ }
+ if (Array.isArray(path)) {
+ path.forEach(function(name) {
+ if (this.path(name)) {
+ delete this.paths[name];
+
+ var pieces = name.split('.');
+ var last = pieces.pop();
+ var branch = this.tree;
+ for (var i = 0; i < pieces.length; ++i) {
+ branch = branch[pieces[i]];
+ }
+ delete branch[last];
+ }
+ }, this);
+ }
+};
+
+/**
+ * Loads an ES6 class into a schema. Maps setters + getters, static methods, and instance methods to schema virtuals, statics, and methods.
+ *
+ * @param {Function} model
+ */
+Schema.prototype.loadClass = function(model, virtualsOnly) {
+ if (model === Object.prototype || model === Function.prototype) {
+ return this;
+ }
+
+ // Add static methods
+ if (!virtualsOnly) {
+ Object.getOwnPropertyNames(model).forEach(function(name) {
+ if (name.match(/^(length|name|prototype)$/)) {
+ return;
+ }
+ var method = Object.getOwnPropertyDescriptor(model, name);
+ if (typeof method.value === 'function') this.static(name, method.value);
+ }, this);
+ }
+
+ // Add methods and virtuals
+ Object.getOwnPropertyNames(model.prototype).forEach(function(name) {
+ if (name.match(/^(constructor)$/)) {
+ return;
+ }
+ var method = Object.getOwnPropertyDescriptor(model.prototype, name);
+ if (!virtualsOnly) {
+ if (typeof method.value === 'function') {
+ this.method(name, method.value);
+ }
+ }
+ if (typeof method.get === 'function') {
+ this.virtual(name).get(method.get);
+ }
+ if (typeof method.set === 'function') {
+ this.virtual(name).set(method.set);
+ }
+ }, this);
+
+ return (this.loadClass(Object.getPrototypeOf(model)));
+};
+
+/*!
+ * ignore
+ */
+
+Schema.prototype._getSchema = function(path) {
+ var _this = this;
+ var pathschema = _this.path(path);
+ var resultPath = [];
+
+ if (pathschema) {
+ pathschema.$fullPath = path;
+ return pathschema;
+ }
+
+ function search(parts, schema) {
+ var p = parts.length + 1,
+ foundschema,
+ trypath;
+
+ while (p--) {
+ trypath = parts.slice(0, p).join('.');
+ foundschema = schema.path(trypath);
+ if (foundschema) {
+ resultPath.push(trypath);
+
+ if (foundschema.caster) {
+ // array of Mixed?
+ if (foundschema.caster instanceof MongooseTypes.Mixed) {
+ foundschema.caster.$fullPath = resultPath.join('.');
+ return foundschema.caster;
+ }
+
+ // Now that we found the array, we need to check if there
+ // are remaining document paths to look up for casting.
+ // Also we need to handle array.$.path since schema.path
+ // doesn't work for that.
+ // If there is no foundschema.schema we are dealing with
+ // a path like array.$
+ if (p !== parts.length && foundschema.schema) {
+ if (parts[p] === '$') {
+ // comments.$.comments.$.title
+ return search(parts.slice(p + 1), foundschema.schema);
+ }
+ // this is the last path of the selector
+ return search(parts.slice(p), foundschema.schema);
+ }
+ }
+
+ foundschema.$fullPath = resultPath.join('.');
+
+ return foundschema;
+ }
+ }
+ }
+
+ // look for arrays
+ return search(path.split('.'), _this);
+};
+
+/*!
+ * ignore
+ */
+
+Schema.prototype._getPathType = function(path) {
+ var _this = this;
+ var pathschema = _this.path(path);
+
+ if (pathschema) {
+ return 'real';
+ }
+
+ function search(parts, schema) {
+ var p = parts.length + 1,
+ foundschema,
+ trypath;
+
+ while (p--) {
+ trypath = parts.slice(0, p).join('.');
+ foundschema = schema.path(trypath);
+ if (foundschema) {
+ if (foundschema.caster) {
+ // array of Mixed?
+ if (foundschema.caster instanceof MongooseTypes.Mixed) {
+ return { schema: foundschema, pathType: 'mixed' };
+ }
+
+ // Now that we found the array, we need to check if there
+ // are remaining document paths to look up for casting.
+ // Also we need to handle array.$.path since schema.path
+ // doesn't work for that.
+ // If there is no foundschema.schema we are dealing with
+ // a path like array.$
+ if (p !== parts.length && foundschema.schema) {
+ if (parts[p] === '$') {
+ if (p === parts.length - 1) {
+ return { schema: foundschema, pathType: 'nested' };
+ }
+ // comments.$.comments.$.title
+ return search(parts.slice(p + 1), foundschema.schema);
+ }
+ // this is the last path of the selector
+ return search(parts.slice(p), foundschema.schema);
+ }
+ return {
+ schema: foundschema,
+ pathType: foundschema.$isSingleNested ? 'nested' : 'array'
+ };
+ }
+ return { schema: foundschema, pathType: 'real' };
+ } else if (p === parts.length && schema.nested[trypath]) {
+ return { schema: schema, pathType: 'nested' };
+ }
+ }
+ return { schema: foundschema || schema, pathType: 'undefined' };
+ }
+
+ // look for arrays
+ return search(path.split('.'), _this);
+};
+
+
+/*!
+ * Module exports.
+ */
+
+module.exports = exports = Schema;
+
+// require down here because of reference issues
+
+/**
+ * The various built-in Mongoose Schema Types.
+ *
+ * ####Example:
+ *
+ * var mongoose = require('mongoose');
+ * var ObjectId = mongoose.Schema.Types.ObjectId;
+ *
+ * ####Types:
+ *
+ * - [String](#schema-string-js)
+ * - [Number](#schema-number-js)
+ * - [Boolean](#schema-boolean-js) | Bool
+ * - [Array](#schema-array-js)
+ * - [Buffer](#schema-buffer-js)
+ * - [Date](#schema-date-js)
+ * - [ObjectId](#schema-objectid-js) | Oid
+ * - [Mixed](#schema-mixed-js)
+ *
+ * Using this exposed access to the `Mixed` SchemaType, we can use them in our schema.
+ *
+ * var Mixed = mongoose.Schema.Types.Mixed;
+ * new mongoose.Schema({ _user: Mixed })
+ *
+ * @api public
+ */
+
+Schema.Types = MongooseTypes = require('./schema/index');
+
+/*!
+ * ignore
+ */
+
+exports.ObjectId = MongooseTypes.ObjectId;
diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/schema/array.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/schema/array.js
new file mode 100644
index 0000000..06a708a
--- /dev/null
+++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/schema/array.js
@@ -0,0 +1,314 @@
+/*!
+ * Module dependencies.
+ */
+
+var SchemaType = require('../schematype');
+var CastError = SchemaType.CastError;
+var Types = {
+ Boolean: require('./boolean'),
+ Date: require('./date'),
+ Number: require('./number'),
+ String: require('./string'),
+ ObjectId: require('./objectid'),
+ Buffer: require('./buffer')
+};
+var MongooseArray = require('../types').Array;
+var EmbeddedDoc = require('../types').Embedded;
+var Mixed = require('./mixed');
+var cast = require('../cast');
+var util = require('util');
+var utils = require('../utils');
+var castToNumber = require('./operators/helpers').castToNumber;
+var geospatial = require('./operators/geospatial');
+
+/**
+ * Array SchemaType constructor
+ *
+ * @param {String} key
+ * @param {SchemaType} cast
+ * @param {Object} options
+ * @inherits SchemaType
+ * @api public
+ */
+
+function SchemaArray(key, cast, options, schemaOptions) {
+ var typeKey = 'type';
+ if (schemaOptions && schemaOptions.typeKey) {
+ typeKey = schemaOptions.typeKey;
+ }
+
+ if (cast) {
+ var castOptions = {};
+
+ if (utils.getFunctionName(cast.constructor) === 'Object') {
+ if (cast[typeKey]) {
+ // support { type: Woot }
+ castOptions = utils.clone(cast); // do not alter user arguments
+ delete castOptions[typeKey];
+ cast = cast[typeKey];
+ } else {
+ cast = Mixed;
+ }
+ }
+
+ // support { type: 'String' }
+ var name = typeof cast === 'string'
+ ? cast
+ : utils.getFunctionName(cast);
+
+ var caster = name in Types
+ ? Types[name]
+ : cast;
+
+ this.casterConstructor = caster;
+ if (typeof caster === 'function') {
+ this.caster = new caster(null, castOptions);
+ } else {
+ this.caster = caster;
+ }
+
+ if (!(this.caster instanceof EmbeddedDoc)) {
+ this.caster.path = key;
+ }
+ }
+
+ SchemaType.call(this, key, options, 'Array');
+
+ var defaultArr;
+ var fn;
+
+ if (this.defaultValue != null) {
+ defaultArr = this.defaultValue;
+ fn = typeof defaultArr === 'function';
+ }
+
+ if (!('defaultValue' in this) || this.defaultValue !== void 0) {
+ this.default(function() {
+ var arr = [];
+ if (fn) {
+ arr = defaultArr();
+ } else if (defaultArr != null) {
+ arr = defaultArr;
+ }
+ // Leave it up to `cast()` to convert the array
+ return arr;
+ });
+ }
+}
+
+/**
+ * This schema type's name, to defend against minifiers that mangle
+ * function names.
+ *
+ * @api public
+ */
+SchemaArray.schemaName = 'Array';
+
+/*!
+ * Inherits from SchemaType.
+ */
+SchemaArray.prototype = Object.create(SchemaType.prototype);
+SchemaArray.prototype.constructor = SchemaArray;
+
+/**
+ * Check if the given value satisfies a required validator. The given value
+ * must be not null nor undefined, and have a non-zero length.
+ *
+ * @param {Any} value
+ * @return {Boolean}
+ * @api public
+ */
+
+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 (pathIndex === '2dsphere' || pathIndex === '2d') {
+ return;
+ }
+ }
+ }
+
+ if (!(value && value.isMongooseArray)) {
+ value = new MongooseArray(value, this.path, doc);
+ } else if (value && value.isMongooseArray) {
+ // We need to create a new array, otherwise change tracking will
+ // update the old doc (gh-4449)
+ value = new MongooseArray(value, this.path, doc);
+ }
+
+ if (this.caster) {
+ try {
+ for (i = 0, l = value.length; i < l; i++) {
+ value[i] = this.caster.cast(value[i], doc, init);
+ }
+ } catch (e) {
+ // rethrow
+ throw new CastError('[' + e.kind + ']', util.inspect(value), this.path, e);
+ }
+ }
+
+ return value;
+ }
+ // 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 && (proto.castForQuery || proto.cast);
+ var caster = this.caster;
+
+ if (Array.isArray(val)) {
+ val = val.map(function(v) {
+ if (utils.isObject(v) && v.$elemMatch) {
+ return v;
+ }
+ if (method) {
+ v = method.call(caster, v);
+ }
+ return v;
+ });
+ } else if (method) {
+ val = method.call(caster, val);
+ }
+ }
+
+ 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 keys = Object.keys(val);
+ var numKeys = keys.length;
+ var key;
+ var value;
+ for (var i = 0; i < numKeys; ++i) {
+ key = keys[i];
+ value = val[key];
+ if (key.indexOf('$') === 0 && value) {
+ val[key] = this.castForQuery(key, value);
+ }
+ }
+
+ return cast(this.casterConstructor.schema, val);
+}
+
+var handle = SchemaArray.prototype.$conditionalHandlers = {};
+
+handle.$all = cast$all;
+handle.$options = String;
+handle.$elemMatch = cast$elemMatch;
+handle.$geoIntersects = geospatial.cast$geoIntersects;
+handle.$or = handle.$and = function(val) {
+ if (!Array.isArray(val)) {
+ throw new TypeError('conditional $or/$and require array');
+ }
+
+ var ret = [];
+ for (var i = 0; i < val.length; ++i) {
+ ret.push(cast(this.casterConstructor.schema, val[i]));
+ }
+
+ return ret;
+};
+
+handle.$near =
+handle.$nearSphere = geospatial.cast$near;
+
+handle.$within =
+handle.$geoWithin = geospatial.cast$within;
+
+handle.$size =
+handle.$minDistance =
+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;
diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/schema/boolean.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/schema/boolean.js
new file mode 100644
index 0000000..206d9fd
--- /dev/null
+++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/schema/boolean.js
@@ -0,0 +1,103 @@
+/*!
+ * Module dependencies.
+ */
+
+var utils = require('../utils');
+
+var SchemaType = require('../schematype');
+
+/**
+ * Boolean SchemaType constructor.
+ *
+ * @param {String} path
+ * @param {Object} options
+ * @inherits SchemaType
+ * @api public
+ */
+
+function SchemaBoolean(path, options) {
+ SchemaType.call(this, path, options, 'Boolean');
+}
+
+/**
+ * This schema type's name, to defend against minifiers that mangle
+ * function names.
+ *
+ * @api public
+ */
+SchemaBoolean.schemaName = 'Boolean';
+
+/*!
+ * Inherits from SchemaType.
+ */
+SchemaBoolean.prototype = Object.create(SchemaType.prototype);
+SchemaBoolean.prototype.constructor = SchemaBoolean;
+
+/**
+ * Check if the given value satisfies a required validator. For a boolean
+ * to satisfy a required validator, it must be strictly equal to true or to
+ * false.
+ *
+ * @param {Any} value
+ * @return {Boolean}
+ * @api public
+ */
+
+SchemaBoolean.prototype.checkRequired = function(value) {
+ return value === true || value === false;
+};
+
+/**
+ * Casts to boolean
+ *
+ * @param {Object} value
+ * @api private
+ */
+
+SchemaBoolean.prototype.cast = function(value) {
+ if (value === null) {
+ return value;
+ }
+ if (value === '0') {
+ return false;
+ }
+ if (value === 'true') {
+ return true;
+ }
+ if (value === 'false') {
+ return false;
+ }
+ return !!value;
+};
+
+SchemaBoolean.$conditionalHandlers =
+ utils.options(SchemaType.prototype.$conditionalHandlers, {});
+
+/**
+ * Casts contents for queries.
+ *
+ * @param {String} $conditional
+ * @param {any} val
+ * @api private
+ */
+
+SchemaBoolean.prototype.castForQuery = function($conditional, val) {
+ var handler;
+ if (arguments.length === 2) {
+ handler = SchemaBoolean.$conditionalHandlers[$conditional];
+
+ if (handler) {
+ return handler.call(this, val);
+ }
+
+ return this.cast(val);
+ }
+
+ return this.cast($conditional);
+};
+
+/*!
+ * Module exports.
+ */
+
+module.exports = SchemaBoolean;
diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/schema/buffer.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/schema/buffer.js
new file mode 100644
index 0000000..e7fe814
--- /dev/null
+++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/schema/buffer.js
@@ -0,0 +1,188 @@
+/*!
+ * Module dependencies.
+ */
+
+var handleBitwiseOperator = require('./operators/bitwise');
+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 {Object} options
+ * @inherits SchemaType
+ * @api public
+ */
+
+function SchemaBuffer(key, options) {
+ SchemaType.call(this, key, options, 'Buffer');
+}
+
+/**
+ * This schema type's name, to defend against minifiers that mangle
+ * function names.
+ *
+ * @api public
+ */
+SchemaBuffer.schemaName = 'Buffer';
+
+/*!
+ * Inherits from SchemaType.
+ */
+SchemaBuffer.prototype = Object.create(SchemaType.prototype);
+SchemaBuffer.prototype.constructor = SchemaBuffer;
+
+/**
+ * Check if the given value satisfies a required validator. To satisfy a
+ * required validator, a buffer must not be null or undefined and have
+ * non-zero length.
+ *
+ * @param {Any} value
+ * @param {Document} doc
+ * @return {Boolean}
+ * @api public
+ */
+
+SchemaBuffer.prototype.checkRequired = function(value, doc) {
+ if (SchemaType._isRef(this, value, doc, true)) {
+ return !!value;
+ }
+ 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) {
+ var ret;
+ if (SchemaType._isRef(this, value, doc, init)) {
+ // wait! we may need to cast this to a document
+
+ if (value === null || value === undefined) {
+ return value;
+ }
+
+ // lazy load
+ Document || (Document = require('./../document'));
+
+ if (value instanceof Document) {
+ value.$__.wasPopulated = true;
+ return value;
+ }
+
+ // setting a populated path
+ if (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);
+ 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) {
+ 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 (value === null) {
+ return value;
+ }
+
+ var type = typeof value;
+ if (type === 'string' || type === 'number' || Array.isArray(value)) {
+ if (type === 'number') {
+ value = [value];
+ }
+ ret = new MongooseBuffer(value, [this.path, doc]);
+ return ret;
+ }
+
+ throw new CastError('buffer', value, this.path);
+};
+
+/*!
+ * ignore
+ */
+function handleSingle(val) {
+ return this.castForQuery(val);
+}
+
+SchemaBuffer.prototype.$conditionalHandlers =
+ utils.options(SchemaType.prototype.$conditionalHandlers, {
+ $bitsAllClear: handleBitwiseOperator,
+ $bitsAnyClear: handleBitwiseOperator,
+ $bitsAllSet: handleBitwiseOperator,
+ $bitsAnySet: handleBitwiseOperator,
+ $gt: handleSingle,
+ $gte: handleSingle,
+ $lt: handleSingle,
+ $lte: handleSingle
+ });
+
+/**
+ * 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);
+ }
+ val = $conditional;
+ return this.cast(val).toObject({ transform: false });
+};
+
+/*!
+ * Module exports.
+ */
+
+module.exports = SchemaBuffer;
diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/schema/date.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/schema/date.js
new file mode 100644
index 0000000..b7bcf22
--- /dev/null
+++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/schema/date.js
@@ -0,0 +1,296 @@
+/*!
+ * Module requirements.
+ */
+
+var MongooseError = require('../error');
+var utils = require('../utils');
+
+var SchemaType = require('../schematype');
+
+var CastError = SchemaType.CastError;
+
+/**
+ * Date SchemaType constructor.
+ *
+ * @param {String} key
+ * @param {Object} options
+ * @inherits SchemaType
+ * @api public
+ */
+
+function SchemaDate(key, options) {
+ SchemaType.call(this, key, options, 'Date');
+}
+
+/**
+ * This schema type's name, to defend against minifiers that mangle
+ * function names.
+ *
+ * @api public
+ */
+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 `expireAfterSeconds` 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 || this._index.constructor.name !== 'Object') {
+ this._index = {};
+ }
+
+ this._index.expires = when;
+ utils.expires(this._index);
+ return this;
+};
+
+/**
+ * Check if the given value satisfies a required validator. To satisfy
+ * a required validator, the given value must be an instance of `Date`.
+ *
+ * @param {Any} value
+ * @param {Document} doc
+ * @return {Boolean}
+ * @api public
+ */
+
+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 || MongooseError.messages.Date.min;
+ msg = msg.replace(/{MIN}/, (value === Date.now ? 'Date.now()' : this.cast(value).toString()));
+ var _this = this;
+ this.validators.push({
+ validator: this.minValidator = function(val) {
+ var min = (value === Date.now ? value() : _this.cast(value));
+ return val === null || val.valueOf() >= min.valueOf();
+ },
+ message: msg,
+ type: 'min',
+ min: value
+ });
+ }
+
+ return this;
+};
+
+/**
+ * Sets a maximum date validator.
+ *
+ * ####Example:
+ *
+ * var s = new Schema({ d: { type: Date, max: Date('2014-01-01') })
+ * var M = db.model('M', s)
+ * var m = new M({ d: Date('2014-12-08') })
+ * m.save(function (err) {
+ * console.error(err) // validator error
+ * m.d = Date('2013-12-31');
+ * m.save() // success
+ * })
+ *
+ * // custom error messages
+ * // We can also use the special {MAX} token which will be replaced with the invalid value
+ * var max = [Date('2014-01-01'), 'The value of path `{PATH}` ({VALUE}) exceeds the limit ({MAX}).'];
+ * var schema = new Schema({ d: { type: Date, max: max })
+ * var M = mongoose.model('M', schema);
+ * var s= new M({ d: Date('2014-12-08') });
+ * s.validate(function (err) {
+ * console.log(String(err)) // ValidationError: The value of path `d` (2014-12-08) exceeds the limit (2014-01-01).
+ * })
+ *
+ * @param {Date} maximum date
+ * @param {String} [message] optional custom error message
+ * @return {SchemaType} this
+ * @see Customized Error Messages #error_messages_MongooseError-messages
+ * @api public
+ */
+
+SchemaDate.prototype.max = function(value, message) {
+ if (this.maxValidator) {
+ this.validators = this.validators.filter(function(v) {
+ return v.validator !== this.maxValidator;
+ }, this);
+ }
+
+ if (value) {
+ var msg = message || MongooseError.messages.Date.max;
+ msg = msg.replace(/{MAX}/, (value === Date.now ? 'Date.now()' : this.cast(value).toString()));
+ var _this = this;
+ this.validators.push({
+ validator: this.maxValidator = function(val) {
+ var max = (value === Date.now ? value() : _this.cast(value));
+ return val === null || val.valueOf() <= max.valueOf();
+ },
+ message: msg,
+ type: 'max',
+ max: value
+ });
+ }
+
+ 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 === void 0 || value === '') {
+ return null;
+ }
+
+ if (value instanceof Date) {
+ if (isNaN(value.valueOf())) {
+ throw new CastError('date', value, this.path);
+ }
+
+ return value;
+ }
+
+ var date;
+
+ if (typeof value === 'boolean') {
+ throw new CastError('date', value, this.path);
+ }
+
+ if (value instanceof Number || typeof value === 'number'
+ || String(value) == Number(value)) {
+ // support for timestamps
+ date = new Date(Number(value));
+ } else if (value.valueOf) {
+ // support for moment.js
+ date = new Date(value.valueOf());
+ }
+
+ if (!isNaN(date.valueOf())) {
+ return date;
+ }
+
+ throw new CastError('date', value, this.path);
+};
+
+/*!
+ * Date Query casting.
+ *
+ * @api private
+ */
+
+function handleSingle(val) {
+ return this.cast(val);
+}
+
+SchemaDate.prototype.$conditionalHandlers =
+ utils.options(SchemaType.prototype.$conditionalHandlers, {
+ $gt: handleSingle,
+ $gte: handleSingle,
+ $lt: handleSingle,
+ $lte: handleSingle
+ });
+
+
+/**
+ * Casts contents for queries.
+ *
+ * @param {String} $conditional
+ * @param {any} [value]
+ * @api private
+ */
+
+SchemaDate.prototype.castForQuery = function($conditional, val) {
+ var handler;
+
+ if (arguments.length !== 2) {
+ 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;
diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/schema/documentarray.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/schema/documentarray.js
new file mode 100644
index 0000000..96da049
--- /dev/null
+++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/schema/documentarray.js
@@ -0,0 +1,313 @@
+/* eslint no-empty: 1 */
+
+/*!
+ * Module dependencies.
+ */
+
+var ArrayType = require('./array');
+var CastError = require('../error/cast');
+var MongooseDocumentArray = require('../types/documentarray');
+var SchemaType = require('../schematype');
+var Subdocument = require('../types/embedded');
+var util = require('util');
+
+/**
+ * SubdocsArray SchemaType constructor
+ *
+ * @param {String} key
+ * @param {Schema} schema
+ * @param {Object} options
+ * @inherits SchemaArray
+ * @api public
+ */
+
+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 (i in schema.statics) {
+ EmbeddedDocument[i] = schema.statics[i];
+ }
+
+ EmbeddedDocument.options = options;
+
+ ArrayType.call(this, key, EmbeddedDocument, options);
+
+ this.schema = schema;
+ this.$isMongooseDocumentArray = true;
+ var fn = this.defaultValue;
+
+ if (!('defaultValue' in this) || fn !== void 0) {
+ this.default(function() {
+ var arr = fn.call(this);
+ if (!Array.isArray(arr)) {
+ arr = [arr];
+ }
+ // Leave it up to `cast()` to convert this to a documentarray
+ return arr;
+ });
+ }
+}
+
+/**
+ * This schema type's name, to defend against minifiers that mangle
+ * function names.
+ *
+ * @api public
+ */
+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, options) {
+ var _this = this;
+ SchemaType.prototype.doValidate.call(this, array, function(err) {
+ if (err) {
+ return fn(err);
+ }
+
+ var count = array && array.length;
+ var error;
+
+ if (!count) {
+ return fn();
+ }
+ if (options && options.updateValidator) {
+ return fn();
+ }
+
+ // handle sparse arrays, do not use array.forEach which does not
+ // iterate over sparse elements yet reports array.length including
+ // them :(
+
+ function callback(err) {
+ if (err) {
+ error = err;
+ }
+ --count || fn(error);
+ }
+
+ for (var i = 0, len = count; i < len; ++i) {
+ // sidestep sparse entries
+ var doc = array[i];
+ if (!doc) {
+ --count || fn(error);
+ continue;
+ }
+
+ // If you set the array index directly, the doc might not yet be
+ // a full fledged mongoose subdoc, so make it into one.
+ if (!(doc instanceof Subdocument)) {
+ doc = array[i] = new _this.casterConstructor(doc, array, undefined,
+ undefined, i);
+ }
+
+ // HACK: use $__original_validate to avoid promises so bluebird doesn't
+ // complain
+ if (doc.$__original_validate) {
+ doc.$__original_validate({__noPromise: true}, callback);
+ } else {
+ doc.validate({__noPromise: true}, callback);
+ }
+ }
+ }, 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, options) {
+ 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) &&
+ (!options || !options.skipDocumentArrayCast)) {
+ value = new MongooseDocumentArray(value, this.path, doc);
+ if (prev && prev._handlers) {
+ for (var key in prev._handlers) {
+ doc.removeListener(key, prev._handlers[key]);
+ }
+ }
+ } else if (value && value.isMongooseDocumentArray) {
+ // We need to create a new array, otherwise change tracking will
+ // update the old doc (gh-4449)
+ value = new MongooseDocumentArray(value, this.path, doc);
+ }
+
+ i = value.length;
+
+ while (i--) {
+ if (!value[i]) {
+ continue;
+ }
+ // Check if the document has a different schema (re gh-3701)
+ if ((value[i] instanceof Subdocument) &&
+ value[i].schema !== this.casterConstructor.schema) {
+ value[i] = value[i].toObject({transform: false});
+ }
+ if (!(value[i] instanceof Subdocument) && value[i]) {
+ if (init) {
+ if (doc) {
+ selected || (selected = scopePaths(this, doc.$__.selected, init));
+ } else {
+ selected = true;
+ }
+
+ 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 {
+ try {
+ subdoc = new this.casterConstructor(value[i], value, undefined,
+ undefined, i);
+ // if set() is hooked it will have no return value
+ // see gh-746
+ value[i] = subdoc;
+ } catch (error) {
+ var valueInErrorMessage = util.inspect(value[i]);
+ throw new CastError('embedded', valueInErrorMessage,
+ value._path, error);
+ }
+ }
+ }
+ }
+ }
+
+ 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 (key.indexOf(path) === 0) {
+ hasKeys || (hasKeys = true);
+ selected[key.substring(path.length)] = fields[key];
+ }
+ }
+
+ return hasKeys && selected || undefined;
+}
+
+/*!
+ * Module exports.
+ */
+
+module.exports = DocumentArray;
diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/schema/embedded.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/schema/embedded.js
new file mode 100644
index 0000000..1d3d892
--- /dev/null
+++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/schema/embedded.js
@@ -0,0 +1,177 @@
+'use strict';
+
+/*!
+ * Module dependencies.
+ */
+
+var SchemaType = require('../schematype');
+var Subdocument = require('../types/subdocument');
+var castToNumber = require('./operators/helpers').castToNumber;
+var geospatial = require('./operators/geospatial');
+
+module.exports = Embedded;
+
+/**
+ * Sub-schema schematype constructor
+ *
+ * @param {Schema} schema
+ * @param {String} key
+ * @param {Object} options
+ * @inherits SchemaType
+ * @api public
+ */
+
+function Embedded(schema, path, options) {
+ var _embedded = function(value, path, parent) {
+ var _this = this;
+ Subdocument.apply(this, arguments);
+ this.$parent = parent;
+ if (parent) {
+ parent.on('save', function() {
+ _this.emit('save', _this);
+ });
+
+ parent.on('isNew', function(val) {
+ _this.isNew = val;
+ _this.emit('isNew', val);
+ });
+ }
+ };
+ _embedded.prototype = Object.create(Subdocument.prototype);
+ _embedded.prototype.$__setSchema(schema);
+ _embedded.schema = schema;
+ _embedded.$isSingleNested = true;
+ _embedded.prototype.$basePath = path;
+ _embedded.prototype.toBSON = function() {
+ return this.toObject({
+ transform: false,
+ retainKeyOrder: schema.options.retainKeyOrder
+ });
+ };
+
+ // apply methods
+ for (var i in schema.methods) {
+ _embedded.prototype[i] = schema.methods[i];
+ }
+
+ // apply statics
+ for (i in schema.statics) {
+ _embedded[i] = schema.statics[i];
+ }
+
+ this.caster = _embedded;
+ this.schema = schema;
+ this.$isSingleNested = true;
+ SchemaType.call(this, path, options, 'Embedded');
+}
+
+Embedded.prototype = Object.create(SchemaType.prototype);
+
+/**
+ * Special case for when users use a common location schema to represent
+ * locations for use with $geoWithin.
+ * https://docs.mongodb.org/manual/reference/operator/query/geoWithin/
+ *
+ * @param {Object} val
+ * @api private
+ */
+
+Embedded.prototype.$conditionalHandlers.$geoWithin = function(val) {
+ return { $geometry: this.castForQuery(val.$geometry) };
+};
+
+/*!
+ * ignore
+ */
+
+Embedded.prototype.$conditionalHandlers.$near =
+Embedded.prototype.$conditionalHandlers.$nearSphere = geospatial.cast$near;
+
+Embedded.prototype.$conditionalHandlers.$within =
+Embedded.prototype.$conditionalHandlers.$geoWithin = geospatial.cast$within;
+
+Embedded.prototype.$conditionalHandlers.$geoIntersects =
+ geospatial.cast$geoIntersects;
+
+Embedded.prototype.$conditionalHandlers.$minDistance = castToNumber;
+Embedded.prototype.$conditionalHandlers.$maxDistance = castToNumber;
+
+/**
+ * Casts contents
+ *
+ * @param {Object} value
+ * @api private
+ */
+
+Embedded.prototype.cast = function(val, doc, init) {
+ if (val && val.$isSingleNested) {
+ return val;
+ }
+ var subdoc = new this.caster(void 0, doc ? doc.$__.selected : void 0, doc);
+ if (init) {
+ subdoc.init(val);
+ } else {
+ subdoc.set(val, undefined, true);
+ }
+ return subdoc;
+};
+
+/**
+ * Casts contents for query
+ *
+ * @param {string} [$conditional] optional query operator (like `$eq` or `$in`)
+ * @param {any} value
+ * @api private
+ */
+
+Embedded.prototype.castForQuery = function($conditional, val) {
+ var handler;
+ if (arguments.length === 2) {
+ handler = this.$conditionalHandlers[$conditional];
+ if (!handler) {
+ throw new Error('Can\'t use ' + $conditional);
+ }
+ return handler.call(this, val);
+ }
+ val = $conditional;
+ if (val == null) {
+ return val;
+ }
+
+ return new this.caster(val);
+};
+
+/**
+ * Async validation on this single nested doc.
+ *
+ * @api private
+ */
+
+Embedded.prototype.doValidate = function(value, fn, scope) {
+ SchemaType.prototype.doValidate.call(this, value, function(error) {
+ if (error) {
+ return fn(error);
+ }
+ if (!value) {
+ return fn(null);
+ }
+ value.validate(fn, {__noPromise: true});
+ }, scope);
+};
+
+/**
+ * Synchronously validate this single nested doc
+ *
+ * @api private
+ */
+
+Embedded.prototype.doValidateSync = function(value, scope) {
+ var schemaTypeError = SchemaType.prototype.doValidateSync.call(this, value, scope);
+ if (schemaTypeError) {
+ return schemaTypeError;
+ }
+ if (!value) {
+ return;
+ }
+ return value.validateSync();
+};
diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/schema/index.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/schema/index.js
new file mode 100644
index 0000000..f2935c1
--- /dev/null
+++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/schema/index.js
@@ -0,0 +1,30 @@
+
+/*!
+ * Module exports.
+ */
+
+exports.String = require('./string');
+
+exports.Number = require('./number');
+
+exports.Boolean = require('./boolean');
+
+exports.DocumentArray = require('./documentarray');
+
+exports.Embedded = require('./embedded');
+
+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;
diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/schema/mixed.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/schema/mixed.js
new file mode 100644
index 0000000..e4c23ca
--- /dev/null
+++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/schema/mixed.js
@@ -0,0 +1,80 @@
+/*!
+ * Module dependencies.
+ */
+
+var SchemaType = require('../schematype');
+var utils = require('../utils');
+
+/**
+ * Mixed SchemaType constructor.
+ *
+ * @param {String} path
+ * @param {Object} options
+ * @inherits SchemaType
+ * @api public
+ */
+
+function Mixed(path, options) {
+ if (options && options.default) {
+ var def = options.default;
+ if (Array.isArray(def) && def.length === 0) {
+ // make sure empty array defaults are handled
+ options.default = Array;
+ } else if (!options.shared && utils.isObject(def) && Object.keys(def).length === 0) {
+ // 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 public
+ */
+Mixed.schemaName = 'Mixed';
+
+/*!
+ * Inherits from SchemaType.
+ */
+Mixed.prototype = Object.create(SchemaType.prototype);
+Mixed.prototype.constructor = Mixed;
+
+/**
+ * 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;
diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/schema/number.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/schema/number.js
new file mode 100644
index 0000000..a91f6dd
--- /dev/null
+++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/schema/number.js
@@ -0,0 +1,290 @@
+/*!
+ * Module requirements.
+ */
+
+var SchemaType = require('../schematype');
+var CastError = SchemaType.CastError;
+var handleBitwiseOperator = require('./operators/bitwise');
+var MongooseError = require('../error');
+var utils = require('../utils');
+var Document;
+
+/**
+ * Number SchemaType constructor.
+ *
+ * @param {String} key
+ * @param {Object} options
+ * @inherits SchemaType
+ * @api public
+ */
+
+function SchemaNumber(key, options) {
+ SchemaType.call(this, key, options, 'Number');
+}
+
+/**
+ * This schema type's name, to defend against minifiers that mangle
+ * function names.
+ *
+ * @api public
+ */
+SchemaNumber.schemaName = 'Number';
+
+/*!
+ * Inherits from SchemaType.
+ */
+SchemaNumber.prototype = Object.create(SchemaType.prototype);
+SchemaNumber.prototype.constructor = SchemaNumber;
+
+/**
+ * Check if the given value satisfies a required validator.
+ *
+ * @param {Any} value
+ * @param {Document} doc
+ * @return {Boolean}
+ * @api public
+ */
+
+SchemaNumber.prototype.checkRequired = function checkRequired(value, doc) {
+ if (SchemaType._isRef(this, value, doc, true)) {
+ return !!value;
+ }
+ 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 (value !== null && value !== undefined) {
+ var msg = message || MongooseError.messages.Number.min;
+ msg = msg.replace(/{MIN}/, value);
+ this.validators.push({
+ validator: this.minValidator = function(v) {
+ return v == null || v >= value;
+ },
+ message: msg,
+ type: 'min',
+ min: value
+ });
+ }
+
+ return this;
+};
+
+/**
+ * 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 (value !== null && value !== undefined) {
+ var msg = message || MongooseError.messages.Number.max;
+ msg = msg.replace(/{MAX}/, value);
+ this.validators.push({
+ validator: this.maxValidator = function(v) {
+ return v == null || v <= value;
+ },
+ message: msg,
+ type: 'max',
+ max: value
+ });
+ }
+
+ return this;
+};
+
+/**
+ * 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 (value === null || value === undefined) {
+ return value;
+ }
+
+ // lazy load
+ Document || (Document = require('./../document'));
+
+ if (value instanceof Document) {
+ value.$__.wasPopulated = true;
+ return value;
+ }
+
+ // setting a populated path
+ if (typeof value === 'number') {
+ return value;
+ } else if (Buffer.isBuffer(value) || !utils.isObject(value)) {
+ throw new CastError('number', value, this.path);
+ }
+
+ // 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 && typeof value._id !== 'undefined' ?
+ value._id : // documents
+ value;
+
+ if (!isNaN(val)) {
+ if (val === null) {
+ return val;
+ }
+ if (val === '') {
+ return null;
+ }
+ if (typeof val === 'string' || typeof val === 'boolean') {
+ val = Number(val);
+ }
+ if (val instanceof Number) {
+ return val;
+ }
+ if (typeof val === 'number') {
+ 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 _this = this;
+ if (!Array.isArray(val)) {
+ return [this.cast(val)];
+ }
+ return val.map(function(m) {
+ return _this.cast(m);
+ });
+}
+
+SchemaNumber.prototype.$conditionalHandlers =
+ utils.options(SchemaType.prototype.$conditionalHandlers, {
+ $bitsAllClear: handleBitwiseOperator,
+ $bitsAnyClear: handleBitwiseOperator,
+ $bitsAllSet: handleBitwiseOperator,
+ $bitsAnySet: handleBitwiseOperator,
+ $gt: handleSingle,
+ $gte: handleSingle,
+ $lt: handleSingle,
+ $lte: handleSingle,
+ $mod: 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);
+ }
+ val = this.cast($conditional);
+ return val;
+};
+
+/*!
+ * Module exports.
+ */
+
+module.exports = SchemaNumber;
diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/schema/objectid.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/schema/objectid.js
new file mode 100644
index 0000000..2885823
--- /dev/null
+++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/schema/objectid.js
@@ -0,0 +1,207 @@
+/* eslint no-empty: 1 */
+
+/*!
+ * 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 public
+ */
+
+function ObjectId(key, options) {
+ SchemaType.call(this, key, options, 'ObjectID');
+}
+
+/**
+ * This schema type's name, to defend against minifiers that mangle
+ * function names.
+ *
+ * @api public
+ */
+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 if the given value satisfies a required validator.
+ *
+ * @param {Any} value
+ * @param {Document} doc
+ * @return {Boolean}
+ * @api public
+ */
+
+ObjectId.prototype.checkRequired = function checkRequired(value, doc) {
+ if (SchemaType._isRef(this, value, doc, true)) {
+ return !!value;
+ }
+ 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 (value === null || value === undefined) {
+ return value;
+ }
+
+ // lazy load
+ Document || (Document = require('./../document'));
+
+ if (value instanceof Document) {
+ value.$__.wasPopulated = true;
+ return value;
+ }
+
+ // setting a populated path
+ if (value instanceof oid) {
+ return value;
+ } else if (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 = value;
+ if (!doc.$__.populated ||
+ !doc.$__.populated[path] ||
+ !doc.$__.populated[path].options ||
+ !doc.$__.populated[path].options.options ||
+ !doc.$__.populated[path].options.options.lean) {
+ ret = new pop.options.model(value);
+ ret.$__.wasPopulated = true;
+ }
+
+ return ret;
+ }
+
+ if (value === null || value === undefined) {
+ 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 new oid(value._id.toString());
+ } catch (e) {
+ }
+ }
+ }
+
+ if (value.toString instanceof Function) {
+ try {
+ return new oid(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);
+}
+
+ObjectId.prototype.$conditionalHandlers =
+ utils.options(SchemaType.prototype.$conditionalHandlers, {
+ $gt: handleSingle,
+ $gte: handleSingle,
+ $lt: handleSingle,
+ $lte: handleSingle
+ });
+
+/**
+ * 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);
+ }
+ return this.cast($conditional);
+};
+
+/*!
+ * ignore
+ */
+
+function defaultId() {
+ return new oid();
+}
+
+function resetId(v) {
+ this.$__._id = null;
+ return v;
+}
+
+/*!
+ * Module exports.
+ */
+
+module.exports = ObjectId;
diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/schema/operators/bitwise.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/schema/operators/bitwise.js
new file mode 100644
index 0000000..c1fdd34
--- /dev/null
+++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/schema/operators/bitwise.js
@@ -0,0 +1,36 @@
+/*!
+ * Module requirements.
+ */
+
+var CastError = require('../../error/cast');
+
+/*!
+ * ignore
+ */
+
+function handleBitwiseOperator(val) {
+ var _this = this;
+ if (Array.isArray(val)) {
+ return val.map(function(v) {
+ return _castNumber(_this.path, v);
+ });
+ } else if (Buffer.isBuffer(val)) {
+ return val;
+ }
+ // Assume trying to cast to number
+ return _castNumber(_this.path, val);
+}
+
+/*!
+ * ignore
+ */
+
+function _castNumber(path, num) {
+ var v = Number(num);
+ if (isNaN(v)) {
+ throw new CastError('number', num, path);
+ }
+ return v;
+}
+
+module.exports = handleBitwiseOperator;
diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/schema/operators/geospatial.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/schema/operators/geospatial.js
new file mode 100644
index 0000000..b490d2d
--- /dev/null
+++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/schema/operators/geospatial.js
@@ -0,0 +1,100 @@
+/*!
+ * Module requirements.
+ */
+
+var castArraysOfNumbers = require('./helpers').castArraysOfNumbers;
+var castToNumber = require('./helpers').castToNumber;
+
+/*!
+ * ignore
+ */
+
+exports.cast$geoIntersects = cast$geoIntersects;
+exports.cast$near = cast$near;
+exports.cast$within = cast$within;
+
+function cast$near(val) {
+ var SchemaArray = require('../array');
+
+ if (Array.isArray(val)) {
+ castArraysOfNumbers(val, this);
+ return val;
+ }
+
+ _castMinMaxDistance(this, 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;
+ }
+
+ _castMinMaxDistance(this, val);
+
+ return val;
+}
+
+function cast$within(val) {
+ _castMinMaxDistance(this, val);
+
+ if (val.$box || val.$polygon) {
+ var type = val.$box ? '$box' : '$polygon';
+ val[type].forEach(function(arr) {
+ if (!Array.isArray(arr)) {
+ var msg = 'Invalid $within $box argument. '
+ + 'Expected an array, received ' + arr;
+ throw new TypeError(msg);
+ }
+ arr.forEach(function(v, i) {
+ arr[i] = castToNumber.call(this, v);
+ });
+ });
+ } else if (val.$center || val.$centerSphere) {
+ 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$geoIntersects(val) {
+ var geo = val.$geometry;
+ if (!geo) {
+ return;
+ }
+
+ cast$geometry(val, this);
+ return val;
+}
+
+function _castMinMaxDistance(self, val) {
+ if (val.$maxDistance) {
+ val.$maxDistance = castToNumber.call(self, val.$maxDistance);
+ }
+ if (val.$minDistance) {
+ val.$minDistance = castToNumber.call(self, val.$minDistance);
+ }
+}
diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/schema/operators/helpers.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/schema/operators/helpers.js
new file mode 100644
index 0000000..850354a
--- /dev/null
+++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/schema/operators/helpers.js
@@ -0,0 +1,34 @@
+'use strict';
+
+/*!
+ * Module requirements.
+ */
+
+var Types = {
+ Number: require('../number')
+};
+
+/*!
+ * @ignore
+ */
+
+exports.castToNumber = castToNumber;
+exports.castArraysOfNumbers = castArraysOfNumbers;
+
+/*!
+ * @ignore
+ */
+
+function castToNumber(val) {
+ return Types.Number.prototype.cast.call(this, val);
+}
+
+function castArraysOfNumbers(arr, self) {
+ arr.forEach(function(v, i) {
+ if (Array.isArray(v)) {
+ castArraysOfNumbers(v, self);
+ } else {
+ arr[i] = castToNumber.call(self, v);
+ }
+ });
+}
diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/schema/string.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/schema/string.js
new file mode 100644
index 0000000..eae40b8
--- /dev/null
+++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/schema/string.js
@@ -0,0 +1,516 @@
+/*!
+ * Module dependencies.
+ */
+
+var SchemaType = require('../schematype');
+var CastError = SchemaType.CastError;
+var MongooseError = require('../error');
+var utils = require('../utils');
+var Document;
+
+/**
+ * String SchemaType constructor.
+ *
+ * @param {String} key
+ * @param {Object} options
+ * @inherits SchemaType
+ * @api public
+ */
+
+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 public
+ */
+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']
+ * 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 enum = {
+ * values: ['opening', 'open', 'closing', 'closed'],
+ * 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 (arguments[0] === void 0 || arguments[0] === false) {
+ return this;
+ }
+
+ var values;
+ var errorMessage;
+
+ if (utils.isObject(arguments[0])) {
+ values = arguments[0].values;
+ errorMessage = arguments[0].message;
+ } else {
+ values = arguments;
+ errorMessage = MongooseError.messages.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',
+ enumValues: vals
+ });
+
+ 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(shouldApply) {
+ if (arguments.length > 0 && !shouldApply) {
+ return this;
+ }
+ return this.set(function(v, self) {
+ if (typeof v !== 'string') {
+ 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(shouldApply) {
+ if (arguments.length > 0 && !shouldApply) {
+ return this;
+ }
+ return this.set(function(v, self) {
+ if (typeof v !== 'string') {
+ 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(shouldTrim) {
+ if (arguments.length > 0 && !shouldTrim) {
+ return this;
+ }
+ return this.set(function(v, self) {
+ if (typeof v !== 'string') {
+ v = self.cast(v);
+ }
+ if (v) {
+ return v.trim();
+ }
+ return v;
+ });
+};
+
+/**
+ * Sets a minimum length validator.
+ *
+ * ####Example:
+ *
+ * var schema = new Schema({ postalCode: { type: String, minlength: 5 })
+ * var Address = db.model('Address', schema)
+ * var address = new Address({ postalCode: '9512' })
+ * address.save(function (err) {
+ * console.error(err) // validator error
+ * address.postalCode = '95125';
+ * address.save() // success
+ * })
+ *
+ * // custom error messages
+ * // We can also use the special {MINLENGTH} token which will be replaced with the minimum allowed length
+ * var minlength = [5, 'The value of path `{PATH}` (`{VALUE}`) is shorter than the minimum allowed length ({MINLENGTH}).'];
+ * var schema = new Schema({ postalCode: { type: String, minlength: minlength })
+ * var Address = mongoose.model('Address', schema);
+ * var address = new Address({ postalCode: '9512' });
+ * address.validate(function (err) {
+ * console.log(String(err)) // ValidationError: The value of path `postalCode` (`9512`) is shorter than the minimum length (5).
+ * })
+ *
+ * @param {Number} value minimum string length
+ * @param {String} [message] optional custom error message
+ * @return {SchemaType} this
+ * @see Customized Error Messages #error_messages_MongooseError-messages
+ * @api public
+ */
+
+SchemaString.prototype.minlength = function(value, message) {
+ if (this.minlengthValidator) {
+ this.validators = this.validators.filter(function(v) {
+ return v.validator !== this.minlengthValidator;
+ }, this);
+ }
+
+ if (value !== null && value !== undefined) {
+ var msg = message || MongooseError.messages.String.minlength;
+ msg = msg.replace(/{MINLENGTH}/, value);
+ this.validators.push({
+ validator: this.minlengthValidator = function(v) {
+ return v === null || v.length >= value;
+ },
+ message: msg,
+ type: 'minlength',
+ minlength: value
+ });
+ }
+
+ return this;
+};
+
+/**
+ * Sets a maximum length validator.
+ *
+ * ####Example:
+ *
+ * var schema = new Schema({ postalCode: { type: String, maxlength: 9 })
+ * var Address = db.model('Address', schema)
+ * var address = new Address({ postalCode: '9512512345' })
+ * address.save(function (err) {
+ * console.error(err) // validator error
+ * address.postalCode = '95125';
+ * address.save() // success
+ * })
+ *
+ * // custom error messages
+ * // We can also use the special {MAXLENGTH} token which will be replaced with the maximum allowed length
+ * var maxlength = [9, 'The value of path `{PATH}` (`{VALUE}`) exceeds the maximum allowed length ({MAXLENGTH}).'];
+ * var schema = new Schema({ postalCode: { type: String, maxlength: maxlength })
+ * var Address = mongoose.model('Address', schema);
+ * var address = new Address({ postalCode: '9512512345' });
+ * address.validate(function (err) {
+ * console.log(String(err)) // ValidationError: The value of path `postalCode` (`9512512345`) exceeds the maximum allowed length (9).
+ * })
+ *
+ * @param {Number} value maximum string length
+ * @param {String} [message] optional custom error message
+ * @return {SchemaType} this
+ * @see Customized Error Messages #error_messages_MongooseError-messages
+ * @api public
+ */
+
+SchemaString.prototype.maxlength = function(value, message) {
+ if (this.maxlengthValidator) {
+ this.validators = this.validators.filter(function(v) {
+ return v.validator !== this.maxlengthValidator;
+ }, this);
+ }
+
+ if (value !== null && value !== undefined) {
+ var msg = message || MongooseError.messages.String.maxlength;
+ msg = msg.replace(/{MAXLENGTH}/, value);
+ this.validators.push({
+ validator: this.maxlengthValidator = function(v) {
+ return v === null || v.length <= value;
+ },
+ message: msg,
+ type: 'maxlength',
+ maxlength: value
+ });
+ }
+
+ return this;
+};
+
+/**
+ * Sets a regexp validator.
+ *
+ * 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 || MongooseError.messages.String.match;
+
+ var matchValidator = function(v) {
+ if (!regExp) {
+ return false;
+ }
+
+ var ret = ((v != null && v !== '')
+ ? regExp.test(v)
+ : true);
+ return ret;
+ };
+
+ this.validators.push({
+ validator: matchValidator,
+ message: msg,
+ type: 'regexp',
+ regexp: regExp
+ });
+ return this;
+};
+
+/**
+ * Check if the given value satisfies a required validator.
+ *
+ * @param {Any} value
+ * @param {Document} doc
+ * @return {Boolean}
+ * @api public
+ */
+
+SchemaString.prototype.checkRequired = function checkRequired(value, doc) {
+ if (SchemaType._isRef(this, value, doc, true)) {
+ return !!value;
+ }
+ 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 (value === null || value === undefined) {
+ return value;
+ }
+
+ // lazy load
+ Document || (Document = require('./../document'));
+
+ if (value instanceof Document) {
+ value.$__.wasPopulated = true;
+ return value;
+ }
+
+ // setting a populated path
+ if (typeof value === 'string') {
+ return value;
+ } else if (Buffer.isBuffer(value) || !utils.isObject(value)) {
+ throw new CastError('string', value, this.path);
+ }
+
+ // 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 || value === undefined) {
+ return value;
+ }
+
+ if (typeof value !== 'undefined') {
+ // handle documents being passed
+ if (value._id && typeof value._id === 'string') {
+ 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 _this = this;
+ if (!Array.isArray(val)) {
+ return [this.castForQuery(val)];
+ }
+ return val.map(function(m) {
+ return _this.castForQuery(m);
+ });
+}
+
+SchemaString.prototype.$conditionalHandlers =
+ utils.options(SchemaType.prototype.$conditionalHandlers, {
+ $all: handleArray,
+ $gt: handleSingle,
+ $gte: handleSingle,
+ $lt: handleSingle,
+ $lte: handleSingle,
+ $options: handleSingle,
+ $regex: handleSingle,
+ $not: 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);
+ }
+ val = $conditional;
+ if (Object.prototype.toString.call(val) === '[object RegExp]') {
+ return val;
+ }
+ return this.cast(val);
+};
+
+/*!
+ * Module exports.
+ */
+
+module.exports = SchemaString;
diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/schematype.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/schematype.js
new file mode 100644
index 0000000..3ca3423
--- /dev/null
+++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/schematype.js
@@ -0,0 +1,931 @@
+/*!
+ * Module dependencies.
+ */
+
+var utils = require('./utils');
+var MongooseError = require('./error');
+var CastError = MongooseError.CastError;
+var ValidatorError = MongooseError.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] && typeof this[i] === 'function') {
+ // { unique: true, index: true }
+ if (i === 'index' && 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 (arguments.length === 1) {
+ if (val === void 0) {
+ this.defaultValue = void 0;
+ return void 0;
+ }
+ this.defaultValue = val;
+ return this.defaultValue;
+ } 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 (this._index === false) {
+ if (!bool) {
+ return;
+ }
+ throw new Error('Path "' + this.path + '" may not have `index` set to ' +
+ 'false and `unique` set to true');
+ }
+ if (this._index == null || this._index === true) {
+ this._index = {};
+ } else if (typeof this._index === 'string') {
+ 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 {Boolean} bool
+ * @return {SchemaType} this
+ * @api public
+ */
+
+SchemaType.prototype.text = function(bool) {
+ if (this._index === null || this._index === undefined ||
+ typeof this._index === 'boolean') {
+ this._index = {};
+ } else if (typeof this._index === 'string') {
+ 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 (this._index === null || this._index === undefined ||
+ typeof this._index === 'boolean') {
+ this._index = {};
+ } else if (typeof this._index === 'string') {
+ this._index = {type: this._index};
+ }
+
+ this._index.sparse = bool;
+ return this;
+};
+
+/**
+ * Adds a setter to this schematype.
+ *
+ * ####Example:
+ *
+ * function capitalize (val) {
+ * if (typeof val !== 'string') 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 (typeof fn !== 'function') {
+ 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 (typeof fn !== 'function') {
+ 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 basic 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.');
+ *
+ * // or with dynamic message
+ *
+ * schema.path('name').validate(function (value, respond) {
+ * doStuff(value, function () {
+ * ...
+ * respond(false, 'this message gets to the validation error');
+ * });
+ * }, 'this message does not matter');
+ *
+ * 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 (typeof obj === 'function' || obj && utils.getFunctionName(obj.constructor) === 'RegExp') {
+ 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 = MongooseError.messages.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 && utils.getFunctionName(arg.constructor) === 'Object')) {
+ 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 validator gets added
+ * to the front of this SchemaType's 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 :( ');
+ *
+ * // or make a path conditionally required based on a function
+ * var isOver18 = function() { return this.age >= 18; };
+ * Schema.path('voterRegistrationId').required(isOver18);
+ *
+ * The required validator uses the SchemaType's `checkRequired` function to
+ * determine whether a given value satisfies the required validator. By default,
+ * a value satisfies the required validator if `val != null` (that is, if
+ * the value is not null nor undefined). However, most built-in mongoose schema
+ * types override the default `checkRequired` function:
+ *
+ * @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
+ * @see SchemaArray#checkRequired #schema_array_SchemaArray.checkRequired
+ * @see SchemaBoolean#checkRequired #schema_boolean_SchemaBoolean-checkRequired
+ * @see SchemaBuffer#checkRequired #schema_buffer_SchemaBuffer.schemaName
+ * @see SchemaNumber#checkRequired #schema_number_SchemaNumber-min
+ * @see SchemaObjectId#checkRequired #schema_objectid_ObjectId-auto
+ * @see SchemaString#checkRequired #schema_string_SchemaString-checkRequired
+ * @api public
+ */
+
+SchemaType.prototype.required = function(required, message) {
+ if (required === false) {
+ this.validators = this.validators.filter(function(v) {
+ return v.validator !== this.requiredValidator;
+ }, this);
+
+ this.isRequired = false;
+ return this;
+ }
+
+ var _this = 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(_this.path) && !this.isModified(_this.path)) {
+ return true;
+ }
+
+ return ((typeof required === 'function') && !required.apply(this)) ||
+ _this.checkRequired(v, this);
+ };
+ this.originalRequiredValue = required;
+
+ if (typeof required === 'string') {
+ message = required;
+ required = undefined;
+ }
+
+ var msg = message || MongooseError.messages.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 = typeof this.defaultValue === 'function'
+ ? this.defaultValue.call(scope)
+ : this.defaultValue;
+
+ if (ret !== null && ret !== undefined) {
+ var casted = this.cast(ret, scope, init);
+ if (casted && casted.$isSingleNested) {
+ casted.$parent = scope;
+ }
+ return casted;
+ }
+ return ret;
+};
+
+/**
+ * Applies setters
+ *
+ * @param {Object} value
+ * @param {Object} scope
+ * @param {Boolean} init
+ * @api private
+ */
+
+SchemaType.prototype.applySetters = function(value, scope, init, priorVal, options) {
+ 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 (v === null || v === undefined) {
+ return v;
+ }
+
+ // do not cast until all setters are applied #665
+ v = this.cast(v, scope, init, priorVal, options);
+
+ 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 _this = 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 (typeof validator === 'function') {
+ if (value === undefined && !_this.isRequired) {
+ validate(true, validatorProperties);
+ return;
+ }
+ if (validator.length === 2) {
+ var returnVal = validator.call(scope, value, function(ok, customMsg) {
+ if (typeof returnVal === 'boolean') {
+ return;
+ }
+ if (customMsg) {
+ validatorProperties.message = customMsg;
+ }
+ validate(ok, validatorProperties);
+ });
+ if (typeof returnVal === 'boolean') {
+ validate(returnVal, 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) {
+ err = new ValidatorError(validatorProperties);
+ }
+ };
+
+ var validators = this.validators;
+ if (value === void 0) {
+ if (this.validators.length > 0 && this.validators[0].type === 'required') {
+ validators = [this.validators[0]];
+ } else {
+ return null;
+ }
+ }
+
+ 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 (typeof validator === 'function') {
+ // if not async validators
+ if (validator.length !== 2) {
+ 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 (value == null) {
+ return true;
+ }
+ if (!Buffer.isBuffer(value) && // buffers are objects too
+ value._bsontype !== 'Binary' // 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.castForQuery(val);
+}
+
+/*!
+ * ignore
+ */
+
+function handleArray(val) {
+ var _this = this;
+ if (!Array.isArray(val)) {
+ return [this.castForQuery(val)];
+ }
+ return val.map(function(m) {
+ return _this.castForQuery(m);
+ });
+}
+
+/*!
+ * ignore
+ */
+
+SchemaType.prototype.$conditionalHandlers = {
+ $all: handleArray,
+ $eq: handleSingle,
+ $in: handleArray,
+ $ne: handleSingle,
+ $nin: handleArray,
+ $type: function(val) {
+ if (typeof val !== 'number' && typeof val !== 'string') {
+ throw new Error('$type parameter must be number or string');
+ }
+
+ return val;
+ }
+};
+
+/**
+ * Cast the given value with the given optional query operator.
+ *
+ * @param {String} [$conditional] query operator, like `$eq` or `$in`
+ * @param {any} val
+ * @api private
+ */
+
+SchemaType.prototype.castForQuery = function($conditional, val) {
+ var handler;
+ if (arguments.length === 2) {
+ handler = this.$conditionalHandlers[$conditional];
+ if (!handler) {
+ throw new Error('Can\'t use ' + $conditional);
+ }
+ return handler.call(this, val);
+ }
+ val = $conditional;
+ return this.cast(val);
+};
+
+/**
+ * Default check for if this path satisfies the `required` validator.
+ *
+ * @param {any} val
+ * @api private
+ */
+
+SchemaType.prototype.checkRequired = function(val) {
+ return val != null;
+};
+
+/*!
+ * Module exports.
+ */
+
+module.exports = exports = SchemaType;
+
+exports.CastError = CastError;
+
+exports.ValidatorError = ValidatorError;
diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/services/common.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/services/common.js
new file mode 100644
index 0000000..d125987
--- /dev/null
+++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/services/common.js
@@ -0,0 +1,87 @@
+'use strict';
+
+/*!
+ * Module dependencies.
+ */
+
+var ObjectId = require('../types/objectid');
+var utils = require('../utils');
+
+exports.flatten = flatten;
+exports.modifiedPaths = modifiedPaths;
+
+/*!
+ * ignore
+ */
+
+function flatten(update, path, options) {
+ var keys;
+ if (update && utils.isMongooseObject(update) && !Buffer.isBuffer(update)) {
+ keys = Object.keys(update.toObject({ transform: false }));
+ } else {
+ 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];
+ result[path + key] = val;
+ if (shouldFlatten(val)) {
+ if (options && options.skipArrays && Array.isArray(val)) {
+ continue;
+ }
+ var flat = flatten(val, path + key);
+ for (var k in flat) {
+ result[k] = flat[k];
+ }
+ if (Array.isArray(val)) {
+ result[path + key] = val;
+ }
+ }
+ }
+
+ return result;
+}
+
+/*!
+ * ignore
+ */
+
+function modifiedPaths(update, path, result) {
+ var keys = Object.keys(update || {});
+ var numKeys = keys.length;
+ result = result || {};
+ path = path ? path + '.' : '';
+
+ for (var i = 0; i < numKeys; ++i) {
+ var key = keys[i];
+ var val = update[key];
+
+ result[path + key] = true;
+ if (utils.isMongooseObject(val) && !Buffer.isBuffer(val)) {
+ val = val.toObject({ transform: false });
+ }
+ if (shouldFlatten(val)) {
+ modifiedPaths(val, path + key, result);
+ }
+ }
+
+ return result;
+}
+
+/*!
+ * ignore
+ */
+
+function shouldFlatten(val) {
+ return val &&
+ typeof val === 'object' &&
+ !(val instanceof Date) &&
+ !(val instanceof ObjectId) &&
+ (!Array.isArray(val) || val.length > 0) &&
+ !(val instanceof Buffer);
+}
diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/services/setDefaultsOnInsert.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/services/setDefaultsOnInsert.js
new file mode 100644
index 0000000..36b87d7
--- /dev/null
+++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/services/setDefaultsOnInsert.js
@@ -0,0 +1,96 @@
+'use strict';
+
+var modifiedPaths = require('./common').modifiedPaths;
+
+/**
+ * Applies defaults to update and findOneAndUpdate operations.
+ *
+ * @param {Query} query
+ * @param {Schema} schema
+ * @param {Object} castedDoc
+ * @param {Object} options
+ * @method setDefaultsOnInsert
+ * @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;
+ var modified = {};
+
+ if (options && options.upsert) {
+ for (var i = 0; i < numKeys; ++i) {
+ if (keys[i].charAt(0) === '$') {
+ modifiedPaths(castedDoc[keys[i]], '', modified);
+ hasDollarUpdate = true;
+ }
+ }
+
+ if (!hasDollarUpdate) {
+ modifiedPaths(castedDoc, '', modified);
+ }
+
+ var paths = Object.keys(query._conditions);
+ var numPaths = keys.length;
+ for (i = 0; i < numPaths; ++i) {
+ var path = paths[i];
+ var condition = query._conditions[path];
+ if (condition && typeof condition === 'object') {
+ var conditionKeys = Object.keys(condition);
+ 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[path] = true;
+ modified[path] = true;
+ }
+
+ if (options.setDefaultsOnInsert) {
+ schema.eachPath(function(path, schemaType) {
+ if (path === '_id') {
+ // Ignore _id for now because it causes bugs in 2.4
+ return;
+ }
+ if (schemaType.$isSingleNested) {
+ // Only handle nested schemas 1-level deep to avoid infinite
+ // recursion re: https://github.com/mongodb-js/mongoose-autopopulate/issues/11
+ schemaType.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 (!modified[path + '.' + _path] && typeof def !== 'undefined') {
+ castedDoc = castedDoc || {};
+ castedDoc.$setOnInsert = castedDoc.$setOnInsert || {};
+ castedDoc.$setOnInsert[path + '.' + _path] = def;
+ updatedValues[path + '.' + _path] = def;
+ }
+ });
+ } else {
+ var def = schemaType.getDefault(null, true);
+ if (!modified[path] && typeof def !== 'undefined') {
+ castedDoc = castedDoc || {};
+ castedDoc.$setOnInsert = castedDoc.$setOnInsert || {};
+ castedDoc.$setOnInsert[path] = def;
+ updatedValues[path] = def;
+ }
+ }
+ });
+ }
+ }
+
+ return castedDoc;
+};
diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/services/updateValidators.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/services/updateValidators.js
new file mode 100644
index 0000000..162ea73
--- /dev/null
+++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/services/updateValidators.js
@@ -0,0 +1,100 @@
+/*!
+ * Module dependencies.
+ */
+
+var Mixed = require('../schema/mixed');
+var ValidationError = require('../error/validation');
+var parallel = require('async/parallel');
+var flatten = require('./common').flatten;
+var modifiedPaths = require('./common').modifiedPaths;
+
+/**
+ * Applies validators and defaults to update and findOneAndUpdate 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;
+ var modified = {};
+
+ for (var i = 0; i < numKeys; ++i) {
+ if (keys[i].charAt(0) === '$') {
+ modifiedPaths(castedDoc[keys[i]], '', modified);
+ var flat = flatten(castedDoc[keys[i]]);
+ var paths = Object.keys(flat);
+ var numPaths = paths.length;
+ for (var j = 0; j < numPaths; ++j) {
+ var updatedPath = paths[j].replace('.$.', '.0.');
+ updatedPath = updatedPath.replace(/\.\$$/, '.0');
+ if (keys[i] === '$set' || keys[i] === '$setOnInsert') {
+ updatedValues[updatedPath] = flat[paths[j]];
+ } else if (keys[i] === '$unset') {
+ updatedValues[updatedPath] = undefined;
+ }
+ updatedKeys[updatedPath] = true;
+ }
+ hasDollarUpdate = true;
+ }
+ }
+
+ if (!hasDollarUpdate) {
+ modifiedPaths(castedDoc, '', modified);
+ updatedValues = flatten(castedDoc);
+ updatedKeys = Object.keys(updatedValues);
+ }
+
+ var updates = Object.keys(updatedValues);
+ var numUpdates = updates.length;
+ var validatorsToExecute = [];
+ var validationErrors = [];
+ function iter(i) {
+ var schemaPath = schema._getSchema(updates[i]);
+ if (schemaPath) {
+ // gh-4305: `_getSchema()` will report all sub-fields of a 'Mixed' path
+ // as 'Mixed', so avoid double validating them.
+ if (schemaPath instanceof Mixed && schemaPath.$fullPath !== updates[i]) {
+ return;
+ }
+ validatorsToExecute.push(function(callback) {
+ schemaPath.doValidate(
+ updatedValues[updates[i]],
+ function(err) {
+ if (err) {
+ err.path = updates[i];
+ validationErrors.push(err);
+ }
+ callback(null);
+ },
+ options && options.context === 'query' ? query : null,
+ {updateValidator: true});
+ });
+ }
+ }
+ for (i = 0; i < numUpdates; ++i) {
+ iter(i);
+ }
+
+ return function(callback) {
+ 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);
+ });
+ };
+};
diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/statemachine.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/statemachine.js
new file mode 100644
index 0000000..3bba519
--- /dev/null
+++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/statemachine.js
@@ -0,0 +1,178 @@
+
+/*!
+ * 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 _this = this;
+ var what = arguments.length ? arguments : this.stateNames;
+ return Array.prototype.some.call(what, function(state) {
+ return Object.keys(_this.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 _this = this;
+
+ var paths = states.reduce(function(paths, state) {
+ return paths.concat(Object.keys(_this.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);
+};
diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/types/array.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/types/array.js
new file mode 100644
index 0000000..715b6b6
--- /dev/null
+++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/types/array.js
@@ -0,0 +1,778 @@
+/*!
+ * 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);
+
+ var keysMA = Object.keys(MongooseArray.mixin);
+ var numKeys = keysMA.length;
+ for (var i = 0; i < numKeys; ++i) {
+ arr[keysMA[i]] = MongooseArray.mixin[keysMA[i]];
+ }
+
+ arr._path = path;
+ arr.isMongooseArray = true;
+ arr.validators = [];
+ arr._atomics = {};
+ arr._schema = void 0;
+
+ // 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 = {
+ /*!
+ * ignore
+ */
+ toBSON: function() {
+ return this.toObject({ transform: false });
+ },
+
+ /**
+ * 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 populated = false;
+ var Model;
+
+ if (this._parent) {
+ populated = this._parent.populated(this._path, true);
+ }
+
+ if (populated && value !== null && value !== undefined) {
+ // 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 (embeddedPath != null) {
+ // 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 (op === '$set') {
+ // $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 (op === '$pop' && !('$pop' in atomics)) {
+ var _this = this;
+ this._parent.once('save', function() {
+ _this._popped = _this._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;
+ }
+
+ var selector;
+
+ 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'] = {});
+ if (val[0] instanceof EmbeddedDocument) {
+ selector = pullOp['$or'] || (pullOp['$or'] = []);
+ Array.prototype.push.apply(selector, val.map(function(v) {
+ return v.toObject({transform: false});
+ }));
+ } else {
+ 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 (i === 0) {
+ ret[0] = ['$set', this.toObject({depopulate: 1, transform: false, _isNested: true})];
+ 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, _isNested: true});
+ } else if (Array.isArray(val)) {
+ val = this.toObject.call(val, {depopulate: 1, transform: false, _isNested: true});
+ } else if (val.valueOf) {
+ val = val.valueOf();
+ }
+
+ if (op === '$addToSet') {
+ 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 && this._atomics.constructor.name === 'Object')) {
+ 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, undefined,
+ undefined, {skipDocumentArrayCast: true});
+ 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. Equality is determined by casting
+ * the provided value to an embedded document and comparing using
+ * [the `Document.equals()` function.](./api.html#document_Document-equals)
+ *
+ * ####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
+ *
+ * The first pull call will result in a atomic operation on the database, if pull is called repeatedly without saving the document, a $set operation is used on the complete array instead, overwriting possible changes that happened on the database in the meantime.
+ *
+ * @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 Document) {
+ var some = values.some(function(v) {
+ return mem.equals(v);
+ });
+ if (some) {
+ [].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 || v;
+ }));
+ } 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 = '';
+ if (values[0] instanceof EmbeddedDocument) {
+ type = 'doc';
+ } else if (values[0] instanceof Date) {
+ type = '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) {
+ options._isNested = true;
+ 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;
diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/types/buffer.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/types/buffer.js
new file mode 100644
index 0000000..8be67c8
--- /dev/null
+++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/types/buffer.js
@@ -0,0 +1,273 @@
+/*!
+ * 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 (length === 0 || arguments[0] === null || arguments[0] === undefined) {
+ 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 && typeof path === 'string') {
+ 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 {Number} The number of bytes copied.
+ * @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] = 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 = typeof options === 'number'
+ ? 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 (typeof subtype !== 'number') {
+ 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;
diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/types/documentarray.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/types/documentarray.js
new file mode 100644
index 0000000..f6fb227
--- /dev/null
+++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/types/documentarray.js
@@ -0,0 +1,256 @@
+/*!
+ * Module dependencies.
+ */
+
+var MongooseArray = require('./array'),
+ ObjectId = require('./objectid'),
+ ObjectIdSchema = require('../schema/objectid'),
+ utils = require('../utils'),
+ 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);
+ arr._path = path;
+
+ var props = {
+ isMongooseArray: true,
+ isMongooseDocumentArray: true,
+ validators: [],
+ _atomics: {},
+ _schema: void 0,
+ _handlers: void 0
+ };
+
+ // Values always have to be passed to the constructor to initialize, since
+ // otherwise MongooseArray#push will mark the array as modified to the parent.
+ var keysMA = Object.keys(MongooseArray.mixin);
+ var numKeys = keysMA.length;
+ for (var j = 0; j < numKeys; ++j) {
+ arr[keysMA[j]] = MongooseArray.mixin[keysMA[j]];
+ }
+
+ var keysMDA = Object.keys(MongooseDocumentArray.mixin);
+ numKeys = keysMDA.length;
+ for (var i = 0; i < numKeys; ++i) {
+ arr[keysMDA[i]] = MongooseDocumentArray.mixin[keysMDA[i]];
+ }
+
+ var keysP = Object.keys(props);
+ numKeys = keysP.length;
+ for (var k = 0; k < numKeys; ++k) {
+ arr[keysP[k]] = props[keysP[k]];
+ }
+
+ // 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 );
+MongooseDocumentArray.mixin = {
+ /*!
+ * ignore
+ */
+ toBSON: function() {
+ return this.toObject({ transform: false });
+ },
+
+ /**
+ * Overrides MongooseArray#cast
+ *
+ * @method _cast
+ * @api private
+ * @receiver MongooseDocumentArray
+ */
+
+ _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;
+ }
+
+ if (value === undefined || value === null) {
+ return null;
+ }
+
+ // 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
+ */
+
+ 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 === null || typeof _id === 'undefined') {
+ continue;
+ } else if (_id instanceof Document) {
+ sid || (sid = String(id));
+ if (sid == _id._id) {
+ return this[i];
+ }
+ } else if (!(id instanceof ObjectId) && !(_id instanceof ObjectId)) {
+ if (utils.deepEqual(id, _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
+ */
+
+ toObject: function(options) {
+ return this.map(function(doc) {
+ return doc && doc.toObject(options) || null;
+ });
+ },
+
+ /**
+ * Helper for console.log
+ *
+ * @method inspect
+ * @api public
+ * @receiver MongooseDocumentArray
+ */
+
+ inspect: function() {
+ return Array.prototype.slice.call(this);
+ },
+
+ /**
+ * 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
+ */
+
+ 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
+ */
+
+ notify: function notify(event) {
+ var _this = this;
+ return function notify(val) {
+ var i = _this.length;
+ while (i--) {
+ if (!_this[i]) {
+ continue;
+ }
+ switch (event) {
+ // only swap for save event for now, we may change this to all event types later
+ case 'save':
+ val = _this[i];
+ break;
+ default:
+ // NO-OP
+ break;
+ }
+ _this[i].emit(event, val);
+ }
+ };
+ }
+
+};
+
+/*!
+ * Module exports.
+ */
+
+module.exports = MongooseDocumentArray;
diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/types/embedded.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/types/embedded.js
new file mode 100644
index 0000000..fbeaf6a
--- /dev/null
+++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/types/embedded.js
@@ -0,0 +1,347 @@
+/* eslint no-func-assign: 1 */
+
+/*!
+ * Module dependencies.
+ */
+
+var Document = require('../document_provider')();
+var PromiseProvider = require('../promise_provider');
+
+/**
+ * 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 _this = this;
+ this.on('isNew', function(val) {
+ _this.isNew = val;
+ });
+}
+
+/*!
+ * Inherit from Document
+ */
+EmbeddedDocument.prototype = Object.create(Document.prototype);
+EmbeddedDocument.prototype.constructor = EmbeddedDocument;
+
+EmbeddedDocument.prototype.toBSON = function() {
+ return this.toObject({ transform: false });
+};
+
+/**
+ * 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) {
+ this.$__.activePaths.modify(path);
+ if (!this.__parentArray) {
+ return;
+ }
+
+ 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);
+ }
+};
+
+/*!
+ * ignore
+ */
+
+EmbeddedDocument.prototype.populate = function() {
+ throw new Error('Mongoose does not support calling populate() on nested ' +
+ 'docs. Instead of `doc.arr[0].populate("path")`, use ' +
+ '`doc.populate("arr.0.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 = PromiseProvider.get();
+ return new Promise.ES6(function(resolve) {
+ fn && fn();
+ resolve();
+ });
+};
+
+/*!
+ * Registers remove event listeners for triggering
+ * on subdocuments.
+ *
+ * @param {EmbeddedDocument} sub
+ * @api private
+ */
+
+function registerRemoveListener(sub) {
+ var owner = sub.ownerDocument();
+
+ function emitRemove() {
+ owner.removeListener('save', emitRemove);
+ owner.removeListener('remove', emitRemove);
+ sub.emit('remove', sub);
+ owner = sub = null;
+ }
+
+ owner.on('save', emitRemove);
+ owner.on('remove', emitRemove);
+}
+
+/**
+ * Removes the subdocument from its parent array.
+ *
+ * @param {Object} [options]
+ * @param {Function} [fn]
+ * @api public
+ */
+
+EmbeddedDocument.prototype.remove = function(options, fn) {
+ if ( typeof options === 'function' && !fn ) {
+ fn = options;
+ options = undefined;
+ }
+ if (!this.__parentArray || (options && options.noop)) {
+ fn && fn(null);
+ 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;
+};
+
+/**
+ * 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 this.toObject({ transform: false, retainKeyOrder: true });
+};
+
+/**
+ * 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) {
+ Document.prototype.invalidate.call(this, path, err, val);
+ if (err.name === 'ValidatorError') {
+ return true;
+ }
+ throw err;
+ }
+
+ 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' && this.__parent) {
+ return !this.__parent.$__.validationError ||
+ !this.__parent.$__.validationError.errors[this.$__fullPath(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 = parent.__parent || parent.$parent;
+ }
+
+ this.$__.ownerDocument = parent;
+ return this.$__.ownerDocument;
+};
+
+/**
+ * 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; // eslint-disable-line consistent-this
+ if (!parent.__parent) {
+ return path;
+ }
+
+ var paths = [];
+ while (parent.__parent || parent.$parent) {
+ if (parent.__parent) {
+ paths.unshift(parent.__parentArray._path);
+ } else {
+ paths.unshift(parent.$basePath);
+ }
+ parent = parent.__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;
diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/types/index.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/types/index.js
new file mode 100644
index 0000000..0d01923
--- /dev/null
+++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/types/index.js
@@ -0,0 +1,15 @@
+
+/*!
+ * 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');
+
+exports.Subdocument = require('./subdocument');
diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/types/objectid.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/types/objectid.js
new file mode 100644
index 0000000..9fe0b97
--- /dev/null
+++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/types/objectid.js
@@ -0,0 +1,13 @@
+/**
+ * ObjectId type constructor
+ *
+ * ####Example
+ *
+ * var id = new mongoose.Types.ObjectId;
+ *
+ * @constructor ObjectId
+ */
+
+var ObjectId = require('../drivers').ObjectId;
+
+module.exports = ObjectId;
diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/types/subdocument.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/types/subdocument.js
new file mode 100644
index 0000000..911fdf4
--- /dev/null
+++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/types/subdocument.js
@@ -0,0 +1,152 @@
+var Document = require('../document');
+var PromiseProvider = require('../promise_provider');
+
+module.exports = Subdocument;
+
+/**
+ * Subdocument constructor.
+ *
+ * @inherits Document
+ * @api private
+ */
+
+function Subdocument(value, fields) {
+ this.$isSingleNested = true;
+ Document.call(this, value, fields);
+}
+
+Subdocument.prototype = Object.create(Document.prototype);
+
+Subdocument.prototype.toBSON = function() {
+ return this.toObject({ transform: false });
+};
+
+/**
+ * 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
+ */
+
+Subdocument.prototype.save = function(fn) {
+ var Promise = PromiseProvider.get();
+ return new Promise.ES6(function(resolve) {
+ fn && fn();
+ resolve();
+ });
+};
+
+Subdocument.prototype.$isValid = function(path) {
+ if (this.$parent) {
+ return this.$parent.$isValid([this.$basePath, path].join('.'));
+ }
+};
+
+Subdocument.prototype.markModified = function(path) {
+ Document.prototype.markModified.call(this, path);
+ if (this.$parent) {
+ if (this.$parent.isDirectModified(this.$basePath)) {
+ return;
+ }
+ this.$parent.markModified([this.$basePath, path].join('.'));
+ }
+};
+
+Subdocument.prototype.$markValid = function(path) {
+ if (this.$parent) {
+ this.$parent.$markValid([this.$basePath, path].join('.'));
+ }
+};
+
+Subdocument.prototype.invalidate = function(path, err, val) {
+ Document.prototype.invalidate.call(this, path, err, val);
+ if (this.$parent) {
+ this.$parent.invalidate([this.$basePath, path].join('.'), err, val);
+ } else if (err.kind === 'cast' || err.name === 'CastError') {
+ throw err;
+ }
+};
+
+/**
+ * Returns the top level document of this sub-document.
+ *
+ * @return {Document}
+ */
+
+Subdocument.prototype.ownerDocument = function() {
+ if (this.$__.ownerDocument) {
+ return this.$__.ownerDocument;
+ }
+
+ var parent = this.$parent;
+ if (!parent) {
+ return this;
+ }
+
+ while (parent.$parent || parent.__parent) {
+ parent = parent.$parent || parent.__parent;
+ }
+ this.$__.ownerDocument = parent;
+ return this.$__.ownerDocument;
+};
+
+/**
+ * Null-out this subdoc
+ *
+ * @param {Object} [options]
+ * @param {Function} [callback] optional callback for compatibility with Document.prototype.remove
+ */
+
+Subdocument.prototype.remove = function(options, callback) {
+ if (typeof options === 'function') {
+ callback = options;
+ options = null;
+ }
+
+ // If removing entire doc, no need to remove subdoc
+ if (!options || !options.noop) {
+ this.$parent.set(this.$basePath, null);
+ registerRemoveListener(this);
+ }
+
+ if (typeof callback === 'function') {
+ callback(null);
+ }
+};
+
+/*!
+ * ignore
+ */
+
+Subdocument.prototype.populate = function() {
+ throw new Error('Mongoose does not support calling populate() on nested ' +
+ 'docs. Instead of `doc.nested.populate("path")`, use ' +
+ '`doc.populate("nested.path")`');
+};
+
+/*!
+ * Registers remove event listeners for triggering
+ * on subdocuments.
+ *
+ * @param {EmbeddedDocument} sub
+ * @api private
+ */
+
+function registerRemoveListener(sub) {
+ var owner = sub.ownerDocument();
+
+ function emitRemove() {
+ owner.removeListener('save', emitRemove);
+ owner.removeListener('remove', emitRemove);
+ sub.emit('remove', sub);
+ owner = sub = null;
+ }
+
+ owner.on('save', emitRemove);
+ owner.on('remove', emitRemove);
+}
diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/utils.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/utils.js
new file mode 100644
index 0000000..391325f
--- /dev/null
+++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/utils.js
@@ -0,0 +1,868 @@
+/*!
+ * 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 (name === 'system.profile') {
+ return name;
+ }
+ if (name === 'system.indexes') {
+ 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 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 && typeof obj.toJSON === 'function') {
+ return obj.toJSON(options);
+ }
+ 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 || (typeof val !== 'undefined')) {
+ 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 || (typeof val !== 'undefined')) {
+ 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, options) {
+ options = options || {};
+ var keys = Object.keys(from);
+ var i = 0;
+ var len = keys.length;
+ var key;
+
+ if (options.retainKeyOrder) {
+ while (i < len) {
+ key = keys[i++];
+ if (typeof to[key] === 'undefined') {
+ to[key] = from[key];
+ } else if (exports.isObject(from[key])) {
+ merge(to[key], from[key]);
+ } else if (options.overwrite) {
+ to[key] = from[key];
+ }
+ }
+ } else {
+ while (len--) {
+ key = keys[len];
+ if (typeof to[key] === 'undefined') {
+ to[key] = from[key];
+ } else if (exports.isObject(from[key])) {
+ merge(to[key], from[key]);
+ } else if (options.overwrite) {
+ to[key] = from[key];
+ }
+ }
+ }
+};
+
+/*!
+ * toString helper
+ */
+
+var toString = Object.prototype.toString;
+
+/*!
+ * Applies toObject recursively.
+ *
+ * @param {Document|Array|Object} obj
+ * @return {Object}
+ * @api private
+ */
+
+exports.toObject = function toObject(obj) {
+ Document || (Document = require('./document'));
+ var ret;
+
+ if (exports.isNullOrUndefined(obj)) {
+ return obj;
+ }
+
+ if (obj instanceof Document) {
+ return obj.toObject();
+ }
+
+ if (Array.isArray(obj)) {
+ ret = [];
+
+ for (var i = 0, len = obj.length; i < len; ++i) {
+ ret.push(toObject(obj[i]));
+ }
+
+ return ret;
+ }
+
+ if ((obj.constructor && exports.getFunctionName(obj.constructor) === 'Object') ||
+ (!obj.constructor && exports.isObject(obj))) {
+ ret = {};
+
+ for (var k in obj) {
+ ret[k] = toObject(obj[k]);
+ }
+
+ return ret;
+ }
+
+ return obj;
+};
+
+/*!
+ * Determines if `arg` is an object.
+ *
+ * @param {Object|Array|String|Function|RegExp|any} arg
+ * @api private
+ * @return {Boolean}
+ */
+
+exports.isObject = function(arg) {
+ if (Buffer.isBuffer(arg)) {
+ return true;
+ }
+ return toString.call(arg) === '[object Object]';
+};
+
+/*!
+ * 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 (typeof callback !== 'function') {
+ 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.constructor.name === 'Object')) {
+ return;
+ }
+ if (!('expires' in object)) {
+ return;
+ }
+
+ var when;
+ if (typeof object.expires !== 'string') {
+ 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, subPopulate) {
+ this.path = path;
+ this.match = match;
+ this.select = select;
+ this.options = options;
+ this.model = model;
+ if (typeof subPopulate === 'object') {
+ this.populate = subPopulate;
+ }
+ 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, subPopulate) {
+ // 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 (arguments.length === 1) {
+ 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;
+ subPopulate = path.populate;
+ path = path.path;
+ }
+ } else if (typeof model !== 'string' && typeof model !== 'function') {
+ options = match;
+ match = model;
+ model = undefined;
+ }
+
+ if (typeof path !== 'string') {
+ throw new TypeError('utils.populate: invalid path. Expected string. Got typeof `' + typeof path + '`');
+ }
+
+ if (typeof subPopulate === 'object') {
+ subPopulate = exports.populate(subPopulate);
+ }
+
+ var ret = [];
+ var paths = path.split(' ');
+ options = exports.clone(options, { retainKeyOrder: true });
+ for (var i = 0; i < paths.length; ++i) {
+ ret.push(new PopulateOptions(paths[i], select, match, options, model, subPopulate));
+ }
+
+ 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 val === null || val === undefined;
+};
+
+/*!
+ * 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} fromObj
+ * @api private
+ */
+
+exports.mergeClone = function(to, fromObj) {
+ var keys = Object.keys(fromObj);
+ var len = keys.length;
+ var i = 0;
+ var key;
+
+ while (i < len) {
+ key = keys[i++];
+ if (typeof to[key] === 'undefined') {
+ // make sure to retain key order here because of a bug handling the $each
+ // operator in mongodb 2.4.4
+ to[key] = exports.clone(fromObj[key], {retainKeyOrder: 1});
+ } else {
+ if (exports.isObject(fromObj[key])) {
+ var obj = fromObj[key];
+ if (isMongooseObject(fromObj[key]) && !fromObj[key].isMongooseBuffer) {
+ obj = obj.toObject({ transform: false });
+ }
+ if (fromObj[key].isMongooseBuffer) {
+ obj = new Buffer(obj);
+ }
+ exports.mergeClone(to[key], obj);
+ } 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(fromObj[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]);
+ }
+};
diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/virtualtype.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/virtualtype.js
new file mode 100644
index 0000000..f43cbe2
--- /dev/null
+++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongoose/lib/virtualtype.js
@@ -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;