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

401
node_modules/mongoose/lib/schema.js generated vendored
View File

@@ -12,16 +12,14 @@ const SchemaTypeOptions = require('./options/SchemaTypeOptions');
const VirtualOptions = require('./options/VirtualOptions');
const VirtualType = require('./virtualtype');
const addAutoId = require('./helpers/schema/addAutoId');
const applyTimestampsToChildren = require('./helpers/update/applyTimestampsToChildren');
const applyTimestampsToUpdate = require('./helpers/update/applyTimestampsToUpdate');
const arrayParentSymbol = require('./helpers/symbols').arrayParentSymbol;
const get = require('./helpers/get');
const getConstructorName = require('./helpers/getConstructorName');
const getIndexes = require('./helpers/schema/getIndexes');
const handleTimestampOption = require('./helpers/schema/handleTimestampOption');
const merge = require('./helpers/schema/merge');
const mpath = require('mpath');
const readPref = require('./driver').get().ReadPreference;
const symbols = require('./schema/symbols');
const setupTimestamps = require('./helpers/timestamps/setupTimestamps');
const util = require('util');
const utils = require('./utils');
const validateRef = require('./helpers/populate/validateRef');
@@ -41,9 +39,9 @@ let id = 0;
*
* ####Example:
*
* var child = new Schema({ name: String });
* var schema = new Schema({ name: String, age: Number, children: [child] });
* var Tree = mongoose.model('Tree', schema);
* const child = new Schema({ name: String });
* const schema = new Schema({ name: String, age: Number, children: [child] });
* const Tree = mongoose.model('Tree', schema);
*
* // setting schema options
* new Schema({ name: String }, { _id: false, autoIndex: false })
@@ -53,8 +51,10 @@ let id = 0;
* - [autoIndex](/docs/guide.html#autoIndex): bool - defaults to null (which means use the connection's autoIndex option)
* - [autoCreate](/docs/guide.html#autoCreate): bool - defaults to null (which means use the connection's autoCreate option)
* - [bufferCommands](/docs/guide.html#bufferCommands): bool - defaults to true
* - [bufferTimeoutMS](/docs/guide.html#bufferTimeoutMS): number - defaults to 10000 (10 seconds). If `bufferCommands` is enabled, the amount of time Mongoose will wait for connectivity to be restablished before erroring out.
* - [capped](/docs/guide.html#capped): bool - defaults to false
* - [collection](/docs/guide.html#collection): string - no default
* - [discriminatorKey](/docs/guide.html#discriminatorKey): string - defaults to `__t`
* - [id](/docs/guide.html#id): bool - defaults to true
* - [_id](/docs/guide.html#_id): bool - defaults to true
* - [minimize](/docs/guide.html#minimize): bool - controls [document#toObject](#document_Document-toObject) behavior when called manually - defaults to true
@@ -69,7 +69,8 @@ let id = 0;
* - [typePojoToMixed](/docs/guide.html#typePojoToMixed) - boolean - defaults to true. Determines whether a type set to a POJO becomes a Mixed path or a Subdocument
* - [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"
* - [versionKey](/docs/guide.html#versionKey): string or object - defaults to "__v"
* - [optimisticConcurrency](/docs/guide.html#optimisticConcurrency): bool - defaults to false. Set to true to enable [optimistic concurrency](https://thecodebarbarian.com/whats-new-in-mongoose-5-10-optimistic-concurrency.html).
* - [collation](/docs/guide.html#collation): object - defaults to null (which means use no collation)
* - [selectPopulatedPaths](/docs/guide.html#selectPopulatedPaths): boolean - defaults to `true`
* - [skipVersioning](/docs/guide.html#skipVersioning): object - paths to exclude from versioning
@@ -114,6 +115,7 @@ function Schema(obj, options) {
this.plugins = [];
// For internal debugging. Do not use this to try to save a schema in MDB.
this.$id = ++id;
this.mapPaths = [];
this.s = {
hooks: new Kareem()
@@ -180,7 +182,7 @@ function aliasFields(schema, paths) {
})(prop)).
set((function(p) {
return function(v) {
return this.set(p, v);
return this.$set(p, v);
};
})(prop));
}
@@ -228,7 +230,7 @@ Object.defineProperty(Schema.prototype, 'childSchemas', {
*
* ####Example:
*
* var schema = new Schema({ a: String }).add({ b: String });
* const schema = new Schema({ a: String }).add({ b: String });
* schema.obj; // { a: String }
*
* @api public
@@ -294,7 +296,9 @@ Schema.prototype.tree;
*/
Schema.prototype.clone = function() {
const s = new Schema({}, this._userProvidedOptions);
const Constructor = this.base == null ? Schema : this.base.Schema;
const s = new Constructor({}, this._userProvidedOptions);
s.base = this.base;
s.obj = this.obj;
s.options = utils.clone(this.options);
@@ -318,6 +322,7 @@ Schema.prototype.clone = function() {
s.$globalPluginsApplied = this.$globalPluginsApplied;
s.$isRootDiscriminator = this.$isRootDiscriminator;
s.$implicitlyCreated = this.$implicitlyCreated;
s.mapPaths = [].concat(this.mapPaths);
if (this.discriminatorMapping != null) {
s.discriminatorMapping = Object.assign({}, this.discriminatorMapping);
@@ -400,9 +405,11 @@ Schema.prototype.defaultOptions = function(options) {
const baseOptions = get(this, 'base.options', {});
options = utils.options({
strict: 'strict' in baseOptions ? baseOptions.strict : true,
strictQuery: 'strictQuery' in baseOptions ? baseOptions.strictQuery : false,
bufferCommands: true,
capped: false, // { size, max, autoIndexId }
versionKey: '__v',
optimisticConcurrency: false,
discriminatorKey: '__t',
minimize: true,
autoIndex: null,
@@ -422,6 +429,10 @@ Schema.prototype.defaultOptions = function(options) {
options.read = readPref(options.read);
}
if (options.optimisticConcurrency && !options.versionKey) {
throw new MongooseError('Must set `versionKey` if using `optimisticConcurrency`');
}
return options;
};
@@ -445,8 +456,9 @@ Schema.prototype.defaultOptions = function(options) {
*/
Schema.prototype.add = function add(obj, prefix) {
if (obj instanceof Schema) {
if (obj instanceof Schema || (obj != null && obj.instanceOfSchema)) {
merge(this, obj);
return this;
}
@@ -458,9 +470,18 @@ Schema.prototype.add = function add(obj, prefix) {
}
prefix = prefix || '';
// avoid prototype pollution
if (prefix === '__proto__.' || prefix === 'constructor.' || prefix === 'prototype.') {
return this;
}
const keys = Object.keys(obj);
for (const key of keys) {
if (utils.specialProperties.has(key)) {
continue;
}
const fullPath = prefix + key;
if (obj[key] == null) {
@@ -471,7 +492,7 @@ Schema.prototype.add = function add(obj, prefix) {
if (key === '_id' && obj[key] === false) {
continue;
}
if (obj[key] instanceof VirtualType) {
if (obj[key] instanceof VirtualType || get(obj[key], 'constructor.name', null) === 'VirtualType') {
this.virtual(obj[key]);
continue;
}
@@ -559,7 +580,7 @@ Schema.prototype.add = function add(obj, prefix) {
*
* _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(..);
* const schema = new Schema(..);
* schema.methods.init = function () {} // potentially breaking
*/
@@ -583,18 +604,9 @@ reserved.isNew =
reserved.populated =
reserved.remove =
reserved.save =
reserved.schema =
reserved.toObject =
reserved.validate = 1;
/*!
* Document keys to print warnings for
*/
const warnings = {};
warnings.increment = '`increment` should not be used as a schema path name ' +
'unless you have disabled versioning.';
/**
* Gets/sets schema paths.
*
@@ -644,10 +656,6 @@ Schema.prototype.path = function(path, obj) {
throw new Error('`' + firstPieceOfPath + '` may not be used as a schema pathname');
}
if (warnings[path]) {
console.log('WARN: ' + warnings[path]);
}
if (typeof obj === 'object' && utils.hasUserDefinedProperty(obj, 'ref')) {
validateRef(obj.ref, path);
}
@@ -659,6 +667,9 @@ Schema.prototype.path = function(path, obj) {
let fullPath = '';
for (const sub of subpaths) {
if (utils.specialProperties.has(sub)) {
throw new Error('Cannot set special property `' + sub + '` on a schema');
}
fullPath = fullPath += (fullPath.length > 0 ? '.' : '') + sub;
if (!branch[sub]) {
this.nested[fullPath] = true;
@@ -692,23 +703,31 @@ Schema.prototype.path = function(path, obj) {
!utils.hasUserDefinedProperty(obj.of, this.options.typeKey);
_mapType = isInlineSchema ? new Schema(obj.of) : obj.of;
}
if (utils.hasUserDefinedProperty(obj, 'ref')) {
_mapType = { type: _mapType, ref: obj.ref };
}
this.paths[mapPath] = this.interpretAsType(mapPath,
_mapType, this.options);
this.mapPaths.push(this.paths[mapPath]);
schemaType.$__schemaType = this.paths[mapPath];
}
if (schemaType.$isSingleNested) {
for (const key in schemaType.schema.paths) {
for (const key of Object.keys(schemaType.schema.paths)) {
this.singleNestedPaths[path + '.' + key] = schemaType.schema.paths[key];
}
for (const key in schemaType.schema.singleNestedPaths) {
for (const key of Object.keys(schemaType.schema.singleNestedPaths)) {
this.singleNestedPaths[path + '.' + key] =
schemaType.schema.singleNestedPaths[key];
}
for (const key in schemaType.schema.subpaths) {
for (const key of Object.keys(schemaType.schema.subpaths)) {
this.singleNestedPaths[path + '.' + key] =
schemaType.schema.subpaths[key];
}
for (const key of Object.keys(schemaType.schema.nested)) {
this.singleNestedPaths[path + '.' + key] = 'nested';
}
Object.defineProperty(schemaType.schema, 'base', {
configurable: true,
@@ -748,9 +767,11 @@ Schema.prototype.path = function(path, obj) {
// Skip arrays of document arrays
if (_schemaType.$isMongooseDocumentArray) {
_schemaType.$embeddedSchemaType._arrayPath = arrayPath;
_schemaType.$embeddedSchemaType._arrayParentPath = path;
_schemaType = _schemaType.$embeddedSchemaType.clone();
} else {
_schemaType.caster._arrayPath = arrayPath;
_schemaType.caster._arrayParentPath = path;
_schemaType = _schemaType.caster.clone();
}
@@ -765,16 +786,25 @@ Schema.prototype.path = function(path, obj) {
if (schemaType.$isMongooseDocumentArray) {
for (const key of Object.keys(schemaType.schema.paths)) {
this.subpaths[path + '.' + key] = schemaType.schema.paths[key];
schemaType.schema.paths[key].$isUnderneathDocArray = true;
const _schemaType = schemaType.schema.paths[key];
this.subpaths[path + '.' + key] = _schemaType;
if (typeof _schemaType === 'object' && _schemaType != null) {
_schemaType.$isUnderneathDocArray = true;
}
}
for (const key of Object.keys(schemaType.schema.subpaths)) {
this.subpaths[path + '.' + key] = schemaType.schema.subpaths[key];
schemaType.schema.subpaths[key].$isUnderneathDocArray = true;
const _schemaType = schemaType.schema.subpaths[key];
this.subpaths[path + '.' + key] = _schemaType;
if (typeof _schemaType === 'object' && _schemaType != null) {
_schemaType.$isUnderneathDocArray = true;
}
}
for (const key of Object.keys(schemaType.schema.singleNestedPaths)) {
this.subpaths[path + '.' + key] = schemaType.schema.singleNestedPaths[key];
schemaType.schema.singleNestedPaths[key].$isUnderneathDocArray = true;
const _schemaType = schemaType.schema.singleNestedPaths[key];
this.subpaths[path + '.' + key] = _schemaType;
if (typeof _schemaType === 'object' && _schemaType != null) {
_schemaType.$isUnderneathDocArray = true;
}
}
}
@@ -809,7 +839,7 @@ function _getPath(schema, path, cleanPath) {
if (schema.subpaths.hasOwnProperty(cleanPath)) {
return schema.subpaths[cleanPath];
}
if (schema.singleNestedPaths.hasOwnProperty(cleanPath)) {
if (schema.singleNestedPaths.hasOwnProperty(cleanPath) && typeof schema.singleNestedPaths[cleanPath] === 'object') {
return schema.singleNestedPaths[cleanPath];
}
@@ -832,10 +862,11 @@ function _pathToPositionalSyntax(path) {
*/
function getMapPath(schema, path) {
for (const _path of Object.keys(schema.paths)) {
if (!_path.includes('.$*')) {
continue;
}
if (schema.mapPaths.length === 0) {
return null;
}
for (const val of schema.mapPaths) {
const _path = val.path;
const re = new RegExp('^' + _path.replace(/\.\$\*/g, '\\.[^.]+') + '$');
if (re.test(path)) {
return schema.paths[_path];
@@ -869,7 +900,12 @@ Object.defineProperty(Schema.prototype, 'base', {
Schema.prototype.interpretAsType = function(path, obj, options) {
if (obj instanceof SchemaType) {
return obj;
if (obj.path === path) {
return obj;
}
const clone = obj.clone();
clone.path = path;
return clone;
}
// If this schema has an associated Mongoose object, use the Mongoose object's
@@ -900,15 +936,25 @@ Schema.prototype.interpretAsType = function(path, obj, options) {
if (Array.isArray(type) || type === Array || type === 'array' || type === MongooseTypes.Array) {
// if it was specified through { type } look for `cast`
let cast = (type === Array || type === 'array')
? obj.cast
? obj.cast || obj.of
: type[0];
if (cast && cast.instanceOfSchema) {
if (!(cast instanceof Schema)) {
throw new TypeError('Schema for array path `' + path +
'` is from a different copy of the Mongoose module. Please make sure you\'re using the same version ' +
'of Mongoose everywhere with `npm list mongoose`.');
}
return new MongooseTypes.DocumentArray(path, cast, obj);
}
if (cast &&
cast[options.typeKey] &&
cast[options.typeKey].instanceOfSchema) {
if (!(cast[options.typeKey] instanceof Schema)) {
throw new TypeError('Schema for array path `' + path +
'` is from a different copy of the Mongoose module. Please make sure you\'re using the same version ' +
'of Mongoose everywhere with `npm list mongoose`.');
}
return new MongooseTypes.DocumentArray(path, cast[options.typeKey], obj, cast);
}
@@ -935,6 +981,14 @@ Schema.prototype.interpretAsType = function(path, obj, options) {
if (options.hasOwnProperty('typePojoToMixed')) {
childSchemaOptions.typePojoToMixed = options.typePojoToMixed;
}
if (this._userProvidedOptions.hasOwnProperty('_id')) {
childSchemaOptions._id = this._userProvidedOptions._id;
} else if (Schema.Types.DocumentArray.defaultOptions &&
Schema.Types.DocumentArray.defaultOptions._id != null) {
childSchemaOptions._id = Schema.Types.DocumentArray.defaultOptions._id;
}
const childSchema = new Schema(cast, childSchemaOptions);
childSchema.$implicitlyCreated = true;
return new MongooseTypes.DocumentArray(path, childSchema, obj);
@@ -953,6 +1007,11 @@ Schema.prototype.interpretAsType = function(path, obj, options) {
? type
: type.schemaName || utils.getFunctionName(type);
// For Jest 26+, see #10296
if (name === 'ClockDate') {
name = 'Date';
}
if (!MongooseTypes.hasOwnProperty(name)) {
throw new TypeError('Invalid schema configuration: ' +
`\`${name}\` is not a valid type within the array \`${path}\`.` +
@@ -983,6 +1042,10 @@ Schema.prototype.interpretAsType = function(path, obj, options) {
if (name === 'ObjectID') {
name = 'ObjectId';
}
// For Jest 26+, see #10296
if (name === 'ClockDate') {
name = 'Date';
}
if (MongooseTypes[name] == null) {
throw new TypeError(`Invalid schema configuration: \`${name}\` is not ` +
@@ -1108,8 +1171,10 @@ Schema.prototype.pathType = function(path) {
if (this.subpaths.hasOwnProperty(cleanPath) || this.subpaths.hasOwnProperty(path)) {
return 'real';
}
if (this.singleNestedPaths.hasOwnProperty(cleanPath) || this.singleNestedPaths.hasOwnProperty(path)) {
return 'real';
const singleNestedPath = this.singleNestedPaths.hasOwnProperty(cleanPath) || this.singleNestedPaths.hasOwnProperty(path);
if (singleNestedPath) {
return singleNestedPath === 'nested' ? 'nested' : 'real';
}
// Look for maps
@@ -1137,7 +1202,7 @@ Schema.prototype.hasMixedParent = function(path) {
path = '';
for (let i = 0; i < subpaths.length; ++i) {
path = i > 0 ? path + '.' + subpaths[i] : subpaths[i];
if (path in this.paths &&
if (this.paths.hasOwnProperty(path) &&
this.paths[path] instanceof MongooseTypes.Mixed) {
return this.paths[path];
}
@@ -1153,100 +1218,7 @@ Schema.prototype.hasMixedParent = function(path) {
* @api private
*/
Schema.prototype.setupTimestamp = function(timestamps) {
const childHasTimestamp = this.childSchemas.find(withTimestamp);
function withTimestamp(s) {
const ts = s.schema.options.timestamps;
return !!ts;
}
if (!timestamps && !childHasTimestamp) {
return;
}
const createdAt = handleTimestampOption(timestamps, 'createdAt');
const updatedAt = handleTimestampOption(timestamps, 'updatedAt');
const currentTime = timestamps != null && timestamps.hasOwnProperty('currentTime') ?
timestamps.currentTime :
null;
const schemaAdditions = {};
this.$timestamps = { createdAt: createdAt, updatedAt: updatedAt };
if (updatedAt && !this.paths[updatedAt]) {
schemaAdditions[updatedAt] = Date;
}
if (createdAt && !this.paths[createdAt]) {
schemaAdditions[createdAt] = Date;
}
this.add(schemaAdditions);
this.pre('save', function(next) {
const timestampOption = get(this, '$__.saveOptions.timestamps');
if (timestampOption === false) {
return next();
}
const skipUpdatedAt = timestampOption != null && timestampOption.updatedAt === false;
const skipCreatedAt = timestampOption != null && timestampOption.createdAt === false;
const defaultTimestamp = currentTime != null ?
currentTime() :
(this.ownerDocument ? this.ownerDocument() : this).constructor.base.now();
const auto_id = this._id && this._id.auto;
if (!skipCreatedAt && createdAt && !this.get(createdAt) && this.isSelected(createdAt)) {
this.set(createdAt, auto_id ? this._id.getTimestamp() : defaultTimestamp);
}
if (!skipUpdatedAt && updatedAt && (this.isNew || this.isModified())) {
let ts = defaultTimestamp;
if (this.isNew) {
if (createdAt != null) {
ts = this.$__getValue(createdAt);
} else if (auto_id) {
ts = this._id.getTimestamp();
}
}
this.set(updatedAt, ts);
}
next();
});
this.methods.initializeTimestamps = function() {
const ts = currentTime != null ?
currentTime() :
this.constructor.base.now();
if (createdAt && !this.get(createdAt)) {
this.set(createdAt, ts);
}
if (updatedAt && !this.get(updatedAt)) {
this.set(updatedAt, ts);
}
return this;
};
_setTimestampsOnUpdate[symbols.builtInMiddleware] = true;
const opts = { query: true, model: false };
this.pre('findOneAndUpdate', opts, _setTimestampsOnUpdate);
this.pre('replaceOne', opts, _setTimestampsOnUpdate);
this.pre('update', opts, _setTimestampsOnUpdate);
this.pre('updateOne', opts, _setTimestampsOnUpdate);
this.pre('updateMany', opts, _setTimestampsOnUpdate);
function _setTimestampsOnUpdate(next) {
const now = currentTime != null ?
currentTime() :
this.model.base.now();
applyTimestampsToUpdate(now, createdAt, updatedAt, this.getUpdate(),
this.options, this.schema);
applyTimestampsToChildren(now, this.getUpdate(), this.model.schema);
next();
}
return setupTimestamps(this, timestamps);
};
/*!
@@ -1346,11 +1318,11 @@ Schema.prototype.queue = function(name, args) {
};
/**
* Defines a pre hook for the document.
* Defines a pre hook for the model.
*
* ####Example
*
* var toySchema = new Schema({ name: String, created: Date });
* const toySchema = new Schema({ name: String, created: Date });
*
* toySchema.pre('save', function(next) {
* if (!this.created) this.created = new Date;
@@ -1412,7 +1384,7 @@ Schema.prototype.pre = function(name) {
/**
* Defines a post hook for the document
*
* var schema = new Schema(..);
* const schema = new Schema(..);
* schema.post('save', function (doc) {
* console.log('this fired after a document was saved');
* });
@@ -1425,9 +1397,9 @@ Schema.prototype.pre = function(name) {
* console.log('this fired after you ran `updateMany()` or `deleteMany()`);
* });
*
* var Model = mongoose.model('Model', schema);
* const Model = mongoose.model('Model', schema);
*
* var m = new Model(..);
* const m = new Model(..);
* m.save(function(err) {
* console.log('this fires after the `post` hook');
* });
@@ -1506,15 +1478,15 @@ Schema.prototype.plugin = function(fn, opts) {
*
* ####Example
*
* var schema = kittySchema = new Schema(..);
* const schema = kittySchema = new Schema(..);
*
* schema.method('meow', function () {
* console.log('meeeeeoooooooooooow');
* })
*
* var Kitty = mongoose.model('Kitty', schema);
* const Kitty = mongoose.model('Kitty', schema);
*
* var fizz = new Kitty;
* const 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.
@@ -1528,7 +1500,7 @@ Schema.prototype.plugin = function(fn, opts) {
* fizz.purr();
* fizz.scratch();
*
* NOTE: `Schema.method()` adds instance methods to the `Schema.methods` object. You can also add instance methods directly to the `Schema.methods` object as seen in the [guide](./guide.html#methods)
* NOTE: `Schema.method()` adds instance methods to the `Schema.methods` object. You can also add instance methods directly to the `Schema.methods` object as seen in the [guide](/docs/guide.html#methods)
*
* @param {String|Object} method name
* @param {Function} [fn]
@@ -1590,7 +1562,7 @@ Schema.prototype.static = function(name, fn) {
*
* @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.
* @param {String | number} [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
*/
@@ -1607,7 +1579,7 @@ Schema.prototype.index = function(fields, options) {
};
/**
* Sets/gets a schema option.
* Sets a schema option.
*
* ####Example
*
@@ -1640,6 +1612,16 @@ Schema.prototype.set = function(key, value, _tags) {
this.options[key] = value;
this._userProvidedOptions[key] = this.options[key];
break;
case '_id':
this.options[key] = value;
this._userProvidedOptions[key] = this.options[key];
if (value && !this.paths['_id']) {
addAutoId(this);
} else if (!value && this.paths['_id'] != null && this.paths['_id'].auto) {
this.remove('_id');
}
break;
default:
this.options[key] = value;
this._userProvidedOptions[key] = this.options[key];
@@ -1701,8 +1683,8 @@ Object.defineProperty(Schema, 'indexTypes', {
});
/**
* Returns a list of indexes that this schema declares, via `schema.index()`
* or by `index: true` in a path's options.
* Returns a list of indexes that this schema declares, via `schema.index()` or by `index: true` in a path's options.
* Indexes are expressed as an array `[spec, options]`.
*
* ####Example:
*
@@ -1715,6 +1697,17 @@ Object.defineProperty(Schema, 'indexTypes', {
* // [ { registeredAt: 1 }, { background: true } ] ]
* userSchema.indexes();
*
* [Plugins](/docs/plugins.html) can use the return value of this function to modify a schema's indexes.
* For example, the below plugin makes every index unique by default.
*
* function myPlugin(schema) {
* for (const index of schema.indexes()) {
* if (index[1].unique === undefined) {
* index[1].unique = true;
* }
* }
* }
*
* @api public
* @return {Array} list of indexes defined in the schema
*/
@@ -1733,11 +1726,12 @@ Schema.prototype.indexes = function() {
* @param {String|Function} [options.foreignField] Required for populate virtuals. See [populate virtual docs](populate.html#populate-virtuals) for more information.
* @param {Boolean|Function} [options.justOne=false] Only works with populate virtuals. If [truthy](https://masteringjs.io/tutorials/fundamentals/truthy), will be a single doc or `null`. Otherwise, the populate virtual will be an array.
* @param {Boolean} [options.count=false] Only works with populate virtuals. If [truthy](https://masteringjs.io/tutorials/fundamentals/truthy), this populate virtual will contain the number of documents rather than the documents themselves when you `populate()`.
* @param {Function|null} [options.get=null] Adds a [getter](/docs/tutorials/getters-setters.html) to this virtual to transform the populated doc.
* @return {VirtualType}
*/
Schema.prototype.virtual = function(name, options) {
if (name instanceof VirtualType) {
if (name instanceof VirtualType || getConstructorName(name) === 'VirtualType') {
return this.virtual(name.path, name.options);
}
@@ -1775,15 +1769,8 @@ Schema.prototype.virtual = function(name, options) {
const virtual = this.virtual(name);
virtual.options = options;
return virtual.
get(function(_v) {
if (this.$$populatedVirtuals &&
this.$$populatedVirtuals.hasOwnProperty(name)) {
return this.$$populatedVirtuals[name];
}
if (_v == null) return undefined;
return _v;
}).
virtual.
set(function(_v) {
if (!this.$$populatedVirtuals) {
this.$$populatedVirtuals = {};
@@ -1807,6 +1794,12 @@ Schema.prototype.virtual = function(name, options) {
});
}
});
if (typeof options.get === 'function') {
virtual.get(options.get);
}
return virtual;
}
const virtuals = this.virtuals;
@@ -1922,9 +1915,9 @@ function _deletePath(schema, name) {
/**
* Loads an ES6 class into a schema. Maps [setters](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/set) + [getters](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get), [static methods](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/static),
* and [instance methods](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes#Class_body_and_method_definitions)
* to schema [virtuals](http://mongoosejs.com/docs/guide.html#virtuals),
* [statics](http://mongoosejs.com/docs/guide.html#statics), and
* [methods](http://mongoosejs.com/docs/guide.html#methods).
* to schema [virtuals](/docs/guide.html#virtuals),
* [statics](/docs/guide.html#statics), and
* [methods](/docs/guide.html#methods).
*
* ####Example:
*
@@ -1964,17 +1957,17 @@ Schema.prototype.loadClass = function(model, virtualsOnly) {
return this;
}
this.loadClass(Object.getPrototypeOf(model));
this.loadClass(Object.getPrototypeOf(model), virtualsOnly);
// Add static methods
if (!virtualsOnly) {
Object.getOwnPropertyNames(model).forEach(function(name) {
if (name.match(/^(length|name|prototype)$/)) {
if (name.match(/^(length|name|prototype|constructor|__proto__)$/)) {
return;
}
const method = Object.getOwnPropertyDescriptor(model, name);
if (typeof method.value === 'function') {
this.static(name, method.value);
const prop = Object.getOwnPropertyDescriptor(model, name);
if (prop.hasOwnProperty('value')) {
this.static(name, prop.value);
}
}, this);
}
@@ -1991,9 +1984,15 @@ Schema.prototype.loadClass = function(model, virtualsOnly) {
}
}
if (typeof method.get === 'function') {
if (this.virtuals[name]) {
this.virtuals[name].getters = [];
}
this.virtual(name).get(method.get);
}
if (typeof method.set === 'function') {
if (this.virtuals[name]) {
this.virtuals[name].setters = [];
}
this.virtual(name).set(method.set);
}
}, this);
@@ -2039,29 +2038,37 @@ Schema.prototype._getSchema = function(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) {
let ret;
if (parts[p] === '$' || isArrayFilter(parts[p])) {
if (p + 1 === parts.length) {
// comments.$
return foundschema;
if (p !== parts.length) {
if (foundschema.schema) {
let ret;
if (parts[p] === '$' || isArrayFilter(parts[p])) {
if (p + 1 === parts.length) {
// comments.$
return foundschema;
}
// comments.$.comments.$.title
ret = search(parts.slice(p + 1), foundschema.schema);
if (ret) {
ret.$isUnderneathDocArray = ret.$isUnderneathDocArray ||
!foundschema.schema.$isSingleNested;
}
return ret;
}
// comments.$.comments.$.title
ret = search(parts.slice(p + 1), foundschema.schema);
// this is the last path of the selector
ret = search(parts.slice(p), foundschema.schema);
if (ret) {
ret.$isUnderneathDocArray = ret.$isUnderneathDocArray ||
!foundschema.schema.$isSingleNested;
}
return ret;
}
// this is the last path of the selector
ret = search(parts.slice(p), foundschema.schema);
if (ret) {
ret.$isUnderneathDocArray = ret.$isUnderneathDocArray ||
!foundschema.schema.$isSingleNested;
}
return ret;
}
} else if (foundschema.$isSchemaMap) {
if (p + 1 >= parts.length) {
return foundschema;
}
const ret = search(parts.slice(p + 1), foundschema.$__schemaType.schema);
return ret;
}
foundschema.$fullPath = resultPath.join('.');
@@ -2164,23 +2171,23 @@ module.exports = exports = Schema;
*
* ####Example:
*
* var mongoose = require('mongoose');
* var ObjectId = mongoose.Schema.Types.ObjectId;
* const mongoose = require('mongoose');
* const 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)
* - [String](/docs/schematypes.html#strings)
* - [Number](/docs/schematypes.html#numbers)
* - [Boolean](/docs/schematypes.html#booleans) | Bool
* - [Array](/docs/schematypes.html#arrays)
* - [Buffer](/docs/schematypes.html#buffers)
* - [Date](/docs/schematypes.html#dates)
* - [ObjectId](/docs/schematypes.html#objectids) | Oid
* - [Mixed](/docs/schematypes.html#mixed)
*
* Using this exposed access to the `Mixed` SchemaType, we can use them in our schema.
*
* var Mixed = mongoose.Schema.Types.Mixed;
* const Mixed = mongoose.Schema.Types.Mixed;
* new mongoose.Schema({ _user: Mixed })
*
* @api public