@skybloxsystems/ticket-bot
Version:
1,815 lines (1,570 loc) • 126 kB
JavaScript
'use strict';
/*!
* Module dependencies.
*/
const EventEmitter = require('events').EventEmitter;
const InternalCache = require('./internal');
const MongooseError = require('./error/index');
const MixedSchema = require('./schema/mixed');
const ObjectExpectedError = require('./error/objectExpected');
const ObjectParameterError = require('./error/objectParameter');
const ParallelValidateError = require('./error/parallelValidate');
const Schema = require('./schema');
const StrictModeError = require('./error/strict');
const ValidationError = require('./error/validation');
const ValidatorError = require('./error/validator');
const VirtualType = require('./virtualtype');
const promiseOrCallback = require('./helpers/promiseOrCallback');
const cleanModifiedSubpaths = require('./helpers/document/cleanModifiedSubpaths');
const compile = require('./helpers/document/compile').compile;
const defineKey = require('./helpers/document/compile').defineKey;
const flatten = require('./helpers/common').flatten;
const flattenObjectWithDottedPaths = require('./helpers/path/flattenObjectWithDottedPaths');
const get = require('./helpers/get');
const getEmbeddedDiscriminatorPath = require('./helpers/document/getEmbeddedDiscriminatorPath');
const getKeysInSchemaOrder = require('./helpers/schema/getKeysInSchemaOrder');
const handleSpreadDoc = require('./helpers/document/handleSpreadDoc');
const immediate = require('./helpers/immediate');
const isDefiningProjection = require('./helpers/projection/isDefiningProjection');
const isExclusive = require('./helpers/projection/isExclusive');
const inspect = require('util').inspect;
const internalToObjectOptions = require('./options').internalToObjectOptions;
const markArraySubdocsPopulated = require('./helpers/populate/markArraySubdocsPopulated');
const mpath = require('mpath');
const queryhelpers = require('./queryhelpers');
const utils = require('./utils');
const isPromise = require('./helpers/isPromise');
const clone = utils.clone;
const deepEqual = utils.deepEqual;
const isMongooseObject = utils.isMongooseObject;
const arrayAtomicsBackupSymbol = require('./helpers/symbols').arrayAtomicsBackupSymbol;
const arrayAtomicsSymbol = require('./helpers/symbols').arrayAtomicsSymbol;
const documentArrayParent = require('./helpers/symbols').documentArrayParent;
const documentIsModified = require('./helpers/symbols').documentIsModified;
const documentModifiedPaths = require('./helpers/symbols').documentModifiedPaths;
const documentSchemaSymbol = require('./helpers/symbols').documentSchemaSymbol;
const getSymbol = require('./helpers/symbols').getSymbol;
const populateModelSymbol = require('./helpers/symbols').populateModelSymbol;
const scopeSymbol = require('./helpers/symbols').scopeSymbol;
const schemaMixedSymbol = require('./schema/symbols').schemaMixedSymbol;
const parentPaths = require('./helpers/path/parentPaths');
let DocumentArray;
let MongooseArray;
let Embedded;
const specialProperties = utils.specialProperties;
/**
* The core Mongoose document constructor. You should not call this directly,
* the Mongoose [Model constructor](./api.html#Model) calls this for you.
*
* @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 {Object} [options] various configuration options for the document
* @param {Boolean} [options.defaults=true] if `false`, skip applying default values to this document.
* @inherits NodeJS EventEmitter http://nodejs.org/api/events.html#events_class_events_eventemitter
* @event `init`: Emitted on a document after it has been retrieved from the db and fully hydrated by Mongoose.
* @event `save`: Emitted when the document is successfully saved
* @api private
*/
function Document(obj, fields, skipId, options) {
if (typeof skipId === 'object' && skipId != null) {
options = skipId;
skipId = options.skipId;
}
options = Object.assign({}, options);
// Support `browserDocument.js` syntax
if (this.$__schema == null) {
const _schema = utils.isObject(fields) && !fields.instanceOfSchema ?
new Schema(fields) :
fields;
this.$__setSchema(_schema);
fields = skipId;
skipId = options;
options = arguments[4] || {};
}
this.$__ = new InternalCache;
this.$__.emitter = new EventEmitter();
this.$isNew = 'isNew' in options ? options.isNew : true;
if ('priorDoc' in options) {
this.$__.priorDoc = options.priorDoc;
}
if (obj != null && typeof obj !== 'object') {
throw new ObjectParameterError(obj, 'obj', 'Document');
}
let defaults = true;
if (options.defaults !== undefined) {
this.$__.defaults = options.defaults;
defaults = options.defaults;
}
const schema = this.$__schema;
if (typeof fields === 'boolean' || fields === 'throw') {
this.$__.strictMode = fields;
fields = undefined;
} else {
this.$__.strictMode = schema.options.strict;
if (fields !== undefined) {
this.$__.selected = fields;
}
}
const requiredPaths = schema.requiredPaths(true);
for (const path of requiredPaths) {
this.$__.activePaths.require(path);
}
this.$__.emitter.setMaxListeners(0);
let exclude = null;
// determine if this doc is a result of a query with
// excluded fields
if (utils.isPOJO(fields)) {
exclude = isExclusive(fields);
}
const hasIncludedChildren = exclude === false && fields ?
$__hasIncludedChildren(fields) :
{};
if (this._doc == null) {
this.$__buildDoc(obj, fields, skipId, exclude, hasIncludedChildren, false);
// By default, defaults get applied **before** setting initial values
// Re: gh-6155
if (defaults) {
$__applyDefaults(this, fields, skipId, exclude, hasIncludedChildren, true, {
isNew: this.$isNew
});
}
}
if (obj) {
// Skip set hooks
if (this.$__original_set) {
this.$__original_set(obj, undefined, true);
} else {
this.$set(obj, undefined, true);
}
if (obj instanceof Document) {
this.$isNew = obj.$isNew;
}
}
// Function defaults get applied **after** setting initial values so they
// see the full doc rather than an empty one, unless they opt out.
// Re: gh-3781, gh-6155
if (options.willInit && defaults) {
EventEmitter.prototype.once.call(this, 'init', () => {
$__applyDefaults(this, fields, skipId, exclude, hasIncludedChildren, false, options.skipDefaults, {
isNew: this.$isNew
});
});
} else if (defaults) {
$__applyDefaults(this, fields, skipId, exclude, hasIncludedChildren, false, options.skipDefaults, {
isNew: this.$isNew
});
}
this.$__._id = this._id;
if (!this.$__.strictMode && obj) {
const _this = this;
const keys = Object.keys(this._doc);
keys.forEach(function(key) {
// Avoid methods, virtuals, existing fields, and `$` keys. The latter is to avoid overwriting
// Mongoose internals.
if (!(key in schema.tree) && !(key in schema.methods) && !(key in schema.virtuals) && !key.startsWith('$')) {
defineKey({ prop: key, subprops: null, prototype: _this });
}
});
}
applyQueue(this);
}
Object.defineProperty(Document.prototype, 'isNew', {
get: function() {
return this.$isNew;
},
set: function(value) {
this.$isNew = value;
}
});
Object.defineProperty(Document.prototype, 'errors', {
get: function() {
return this.$errors;
},
set: function(value) {
this.$errors = value;
}
});
/*!
* 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[`$${emitterFn}`] = Document.prototype[emitterFn];
});
Document.prototype.constructor = Document;
for (const i in EventEmitter.prototype) {
Document[i] = EventEmitter.prototype[i];
}
/**
* The document's internal schema.
*
* @api private
* @property schema
* @memberOf Document
* @instance
*/
Document.prototype.$__schema;
/**
* The document's schema.
*
* @api public
* @property schema
* @memberOf Document
* @instance
*/
Document.prototype.schema;
/**
* Empty object that you can use for storing properties on the document. This
* is handy for passing data to middleware without conflicting with Mongoose
* internals.
*
* ####Example:
*
* schema.pre('save', function() {
* // Mongoose will set `isNew` to `false` if `save()` succeeds
* this.$locals.wasNew = this.isNew;
* });
*
* schema.post('save', function() {
* // Prints true if `isNew` was set before `save()`
* console.log(this.$locals.wasNew);
* });
*
* @api public
* @property $locals
* @memberOf Document
* @instance
*/
Object.defineProperty(Document.prototype, '$locals', {
configurable: false,
enumerable: false,
get: function() {
if (this.$__.locals == null) {
this.$__.locals = {};
}
return this.$__.locals;
},
set: function(v) {
this.$__.locals = v;
}
});
/**
* Boolean flag specifying if the document is new.
*
* @api public
* @property $isNew
* @memberOf Document
* @instance
*/
Document.prototype.$isNew;
/**
* Boolean flag specifying if the document is new.
*
* @api public
* @property isNew
* @memberOf Document
* @instance
*/
Document.prototype.isNew;
/**
* Set this property to add additional query filters when Mongoose saves this document and `isNew` is false.
*
* ####Example:
*
* // Make sure `save()` never updates a soft deleted document.
* schema.pre('save', function() {
* this.$where = { isDeleted: false };
* });
*
* @api public
* @property $where
* @memberOf Document
* @instance
*/
Object.defineProperty(Document.prototype, '$where', {
configurable: false,
enumerable: false,
writable: true
});
/**
* 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
* @memberOf Document
* @instance
*/
Document.prototype.id;
/**
* Hash containing current validation $errors.
*
* @api public
* @property $errors
* @memberOf Document
* @instance
*/
Document.prototype.$errors;
/**
* Hash containing current validation errors.
*
* @api public
* @property errors
* @memberOf Document
* @instance
*/
Document.prototype.errors;
/**
* A string containing the current operation that Mongoose is executing
* on this document. May be `null`, `'save'`, `'validate'`, or `'remove'`.
*
* ####Example:
*
* const doc = new Model({ name: 'test' });
* doc.$op; // null
*
* const promise = doc.save();
* doc.$op; // 'save'
*
* await promise;
* doc.$op; // null
*
* @api public
* @property $op
* @memberOf Document
* @instance
*/
Object.defineProperty(Document.prototype, '$op', {
get: function() {
return this.$__.op || null;
},
set: function(value) {
this.$__.op = value;
}
});
/*!
* ignore
*/
function $__hasIncludedChildren(fields) {
const hasIncludedChildren = {};
const keys = Object.keys(fields);
for (const key of keys) {
const parts = key.split('.');
const c = [];
for (const part of parts) {
c.push(part);
hasIncludedChildren[c.join('.')] = 1;
}
}
return hasIncludedChildren;
}
/*!
* ignore
*/
function $__applyDefaults(doc, fields, skipId, exclude, hasIncludedChildren, isBeforeSetters, pathsToSkip) {
const paths = Object.keys(doc.$__schema.paths);
const plen = paths.length;
for (let i = 0; i < plen; ++i) {
let def;
let curPath = '';
const p = paths[i];
if (p === '_id' && skipId) {
continue;
}
const type = doc.$__schema.paths[p];
const path = type.splitPath();
const len = path.length;
let included = false;
let doc_ = doc._doc;
for (let j = 0; j < len; ++j) {
if (doc_ == null) {
break;
}
const piece = path[j];
curPath += (!curPath.length ? '' : '.') + piece;
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 (j === len - 1) {
if (doc_[piece] !== void 0) {
break;
}
if (typeof type.defaultValue === 'function') {
if (!type.defaultValue.$runBeforeSetters && isBeforeSetters) {
break;
}
if (type.defaultValue.$runBeforeSetters && !isBeforeSetters) {
break;
}
} else if (!isBeforeSetters) {
// Non-function defaults should always run **before** setters
continue;
}
if (pathsToSkip && pathsToSkip[curPath]) {
break;
}
if (fields && exclude !== null) {
if (exclude === true) {
// apply defaults to all non-excluded fields
if (p in fields) {
continue;
}
try {
def = type.getDefault(doc, false);
} catch (err) {
doc.invalidate(p, err);
break;
}
if (typeof def !== 'undefined') {
doc_[piece] = def;
doc.$__.activePaths.default(p);
}
} else if (included) {
// selected field
try {
def = type.getDefault(doc, false);
} catch (err) {
doc.invalidate(p, err);
break;
}
if (typeof def !== 'undefined') {
doc_[piece] = def;
doc.$__.activePaths.default(p);
}
}
} else {
try {
def = type.getDefault(doc, false);
} catch (err) {
doc.invalidate(p, err);
break;
}
if (typeof def !== 'undefined') {
doc_[piece] = def;
doc.$__.activePaths.default(p);
}
}
} else {
doc_ = doc_[piece];
}
}
}
}
/*!
* ignore
*/
function $applyDefaultsToNested(val, path, doc) {
if (val == null) {
return;
}
flattenObjectWithDottedPaths(val);
const paths = Object.keys(doc.$__schema.paths);
const plen = paths.length;
const pathPieces = path.indexOf('.') === -1 ? [path] : path.split('.');
for (let i = 0; i < plen; ++i) {
let curPath = '';
const p = paths[i];
if (!p.startsWith(path + '.')) {
continue;
}
const type = doc.$__schema.paths[p];
const pieces = type.splitPath().slice(pathPieces.length);
const len = pieces.length;
if (type.defaultValue === void 0) {
continue;
}
let cur = val;
for (let j = 0; j < len; ++j) {
if (cur == null) {
break;
}
const piece = pieces[j];
if (j === len - 1) {
if (cur[piece] !== void 0) {
break;
}
try {
const def = type.getDefault(doc, false);
if (def !== void 0) {
cur[piece] = def;
}
} catch (err) {
doc.invalidate(path + '.' + curPath, err);
break;
}
break;
}
curPath += (!curPath.length ? '' : '.') + piece;
cur[piece] = cur[piece] || {};
cur = cur[piece];
}
}
}
/**
* Builds the default doc structure
*
* @param {Object} obj
* @param {Object} [fields]
* @param {Boolean} [skipId]
* @api private
* @method $__buildDoc
* @memberOf Document
* @instance
*/
Document.prototype.$__buildDoc = function(obj, fields, skipId, exclude, hasIncludedChildren) {
const doc = {};
const paths = Object.keys(this.$__schema.paths).
// Don't build up any paths that are underneath a map, we don't know
// what the keys will be
filter(p => !p.includes('$*'));
const plen = paths.length;
let ii = 0;
for (; ii < plen; ++ii) {
const p = paths[ii];
if (p === '_id') {
if (skipId) {
continue;
}
if (obj && '_id' in obj) {
continue;
}
}
const path = this.$__schema.paths[p].splitPath();
const len = path.length;
const last = len - 1;
let curPath = '';
let doc_ = doc;
let included = false;
for (let i = 0; i < len; ++i) {
const piece = path[i];
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) {
doc_ = doc_[piece] || (doc_[piece] = {});
}
}
}
this._doc = doc;
};
/*!
* Converts to POJO when you use the document for querying
*/
Document.prototype.toBSON = function() {
return this.toObject(internalToObjectOptions);
};
/**
* Initializes the document without setters or marking anything modified.
*
* Called internally after a document is returned from mongodb. Normally,
* you do **not** need to call this function on your own.
*
* This function triggers `init` [middleware](/docs/middleware.html).
* Note that `init` hooks are [synchronous](/docs/middleware.html#synchronous).
*
* @param {Object} doc document returned by mongo
* @api public
* @memberOf Document
* @instance
*/
Document.prototype.init = function(doc, opts, fn) {
if (typeof opts === 'function') {
fn = opts;
opts = null;
}
this.$__init(doc, opts);
if (fn) {
fn(null, this);
}
return this;
};
Document.prototype.$init = function() {
return this.constructor.prototype.init.apply(this, arguments);
};
/*!
* ignore
*/
Document.prototype.$__init = function(doc, opts) {
this.$isNew = false;
opts = opts || {};
// handle docs with populated paths
// If doc._id is not null or undefined
if (doc._id != null && opts.populated && opts.populated.length) {
const id = String(doc._id);
for (const item of opts.populated) {
if (item.isVirtual) {
this.$populated(item.path, utils.getValue(item.path, doc), item);
} else {
this.$populated(item.path, item._docs[id], item);
}
if (item._childDocs == null) {
continue;
}
for (const child of item._childDocs) {
if (child == null || child.$__ == null) {
continue;
}
child.$__.parent = this;
}
item._childDocs = [];
}
}
init(this, doc, this._doc, opts);
markArraySubdocsPopulated(this, opts.populated);
this.$emit('init', this);
this.constructor.emit('init', this);
this.$__._id = this._id;
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, opts, prefix) {
prefix = prefix || '';
const keys = Object.keys(obj);
const len = keys.length;
let schema;
let path;
let i;
let index = 0;
const strict = self.$__.strictMode;
while (index < len) {
_init(index++);
}
function _init(index) {
i = keys[index];
path = prefix + i;
schema = self.$__schema.path(path);
// Should still work if not a model-level discriminator, but should not be
// necessary. This is *only* to catch the case where we queried using the
// base model and the discriminated model has a projection
if (self.$__schema.$isRootDiscriminator && !self.$__isSelected(path)) {
return;
}
if (!schema && utils.isPOJO(obj[i])) {
// assume nested object
if (!doc[i]) {
doc[i] = {};
}
init(self, obj[i], doc[i], opts, path + '.');
} else if (!schema) {
doc[i] = obj[i];
if (!strict && !prefix) {
// Set top-level properties that aren't in the schema if strict is false
self[i] = obj[i];
}
} else {
// Retain order when overwriting defaults
if (doc.hasOwnProperty(i) && obj[i] !== void 0) {
delete doc[i];
}
if (obj[i] === null) {
doc[i] = schema._castNullish(null);
} else if (obj[i] !== undefined) {
const intCache = obj[i].$__ || {};
const wasPopulated = intCache.wasPopulated || null;
if (schema && !wasPopulated) {
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,
reason: e
}));
}
} else {
doc[i] = obj[i];
}
}
// mark as hydrated
if (!self.$isModified(path)) {
self.$__.activePaths.init(path);
}
}
}
}
/**
* 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
* @memberOf Document
* @instance
*/
Document.prototype.update = function update() {
const args = utils.args(arguments);
args.unshift({ _id: this._id });
const query = this.constructor.update.apply(this.constructor, args);
if (this.$session() != null) {
if (!('session' in query.options)) {
query.options.session = this.$session();
}
}
return query;
};
/**
* Sends an updateOne command with this document `_id` as the query selector.
*
* ####Example:
*
* weirdCar.updateOne({$inc: {wheels:1}}, { w: 1 }, callback);
*
* ####Valid options:
*
* - same as in [Model.updateOne](#model_Model.updateOne)
*
* @see Model.updateOne #model_Model.updateOne
* @param {Object} doc
* @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions)
* @param {Object} [options.lean] if truthy, mongoose will return the document as a plain JavaScript object rather than a mongoose document. See [`Query.lean()`](/docs/api.html#query_Query-lean) and the [Mongoose lean tutorial](/docs/tutorials/lean.html).
* @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict)
* @param {Boolean} [options.timestamps=null] If set to `false` and [schema-level timestamps](/docs/guide.html#timestamps) are enabled, skip timestamps for this update. Note that this allows you to overwrite timestamps. Does nothing if schema-level timestamps are not set.
* @param {Function} callback
* @return {Query}
* @api public
* @memberOf Document
* @instance
*/
Document.prototype.updateOne = function updateOne(doc, options, callback) {
const query = this.constructor.updateOne({ _id: this._id }, doc, options);
query.pre(cb => {
this.constructor._middleware.execPre('updateOne', this, [this], cb);
});
query.post(cb => {
this.constructor._middleware.execPost('updateOne', this, [this], {}, cb);
});
if (this.$session() != null) {
if (!('session' in query.options)) {
query.options.session = this.$session();
}
}
if (callback != null) {
return query.exec(callback);
}
return query;
};
/**
* Sends a replaceOne command with this document `_id` as the query selector.
*
* ####Valid options:
*
* - same as in [Model.replaceOne](https://mongoosejs.com/docs/api/model.html#model_Model.replaceOne)
*
* @see Model.replaceOne #model_Model.replaceOne
* @param {Object} doc
* @param {Object} options
* @param {Function} callback
* @return {Query}
* @api public
* @memberOf Document
* @instance
*/
Document.prototype.replaceOne = function replaceOne() {
const args = utils.args(arguments);
args.unshift({ _id: this._id });
return this.constructor.replaceOne.apply(this.constructor, args);
};
/**
* Getter/setter around the session associated with this document. Used to
* automatically set `session` if you `save()` a doc that you got from a
* query with an associated session.
*
* ####Example:
*
* const session = MyModel.startSession();
* const doc = await MyModel.findOne().session(session);
* doc.$session() === session; // true
* doc.$session(null);
* doc.$session() === null; // true
*
* If this is a top-level document, setting the session propagates to all child
* docs.
*
* @param {ClientSession} [session] overwrite the current session
* @return {ClientSession}
* @method $session
* @api public
* @memberOf Document
*/
Document.prototype.$session = function $session(session) {
if (arguments.length === 0) {
if (this.$__.session != null && this.$__.session.hasEnded) {
this.$__.session = null;
return null;
}
return this.$__.session;
}
if (session != null && session.hasEnded) {
throw new MongooseError('Cannot set a document\'s session to a session that has ended. Make sure you haven\'t ' +
'called `endSession()` on the session you are passing to `$session()`.');
}
if (session == null && this.$__.session == null) {
return;
}
this.$__.session = session;
if (!this.$isSubdocument) {
const subdocs = this.$getAllSubdocs();
for (const child of subdocs) {
child.$session(session);
}
}
return session;
};
/**
* Overwrite all values in this document with the values of `obj`, except
* for immutable properties. Behaves similarly to `set()`, except for it
* unsets all properties that aren't in `obj`.
*
* @param {Object} obj the object to overwrite this document with
* @method overwrite
* @name overwrite
* @memberOf Document
* @instance
* @api public
*/
Document.prototype.overwrite = function overwrite(obj) {
const keys = Array.from(new Set(Object.keys(this._doc).concat(Object.keys(obj))));
for (const key of keys) {
if (key === '_id') {
continue;
}
// Explicitly skip version key
if (this.$__schema.options.versionKey && key === this.$__schema.options.versionKey) {
continue;
}
if (this.$__schema.options.discriminatorKey && key === this.$__schema.options.discriminatorKey) {
continue;
}
this.$set(key, obj[key]);
}
return this;
};
/**
* Alias for `set()`, used internally to avoid conflicts
*
* @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
* @method $set
* @name $set
* @memberOf Document
* @instance
* @api public
*/
Document.prototype.$set = function $set(path, val, type, options) {
if (utils.isPOJO(type)) {
options = type;
type = undefined;
}
options = options || {};
const merge = options.merge;
const adhoc = type && type !== true;
const constructing = type === true;
const typeKey = this.$__schema.options.typeKey;
let adhocs;
let keys;
let i = 0;
let pathtype;
let key;
let prefix;
const strict = 'strict' in options
? options.strict
: this.$__.strictMode;
if (adhoc) {
adhocs = this.$__.adhocPaths || (this.$__.adhocPaths = {});
adhocs[path] = this.$__schema.interpretAsType(path, type, this.$__schema.options);
}
if (path == null) {
[path, val] = [val, path];
} else if (typeof path !== 'string') {
// new Document({ key: val })
if (path instanceof Document) {
if (path.$__isNested) {
path = path.toObject();
} else {
path = path._doc;
}
}
if (path == null) {
[path, val] = [val, path];
}
prefix = val ? val + '.' : '';
keys = getKeysInSchemaOrder(this.$__schema, path);
const len = keys.length;
// `_skipMinimizeTopLevel` is because we may have deleted the top-level
// nested key to ensure key order.
const _skipMinimizeTopLevel = get(options, '_skipMinimizeTopLevel', false);
if (len === 0 && _skipMinimizeTopLevel) {
delete options._skipMinimizeTopLevel;
if (val) {
this.$set(val, {});
}
return this;
}
for (let i = 0; i < len; ++i) {
key = keys[i];
const pathName = prefix + key;
pathtype = this.$__schema.pathType(pathName);
const valForKey = path[key];
// On initial set, delete any nested keys if we're going to overwrite
// them to ensure we keep the user's key order.
if (type === true &&
!prefix &&
path[key] != null &&
pathtype === 'nested' &&
this._doc[key] != null) {
delete this._doc[key];
// Make sure we set `{}` back even if we minimize re: gh-8565
options = Object.assign({}, options, { _skipMinimizeTopLevel: true });
} else {
// Make sure we set `{_skipMinimizeTopLevel: false}` if don't have overwrite: gh-10441
options = Object.assign({}, options, { _skipMinimizeTopLevel: false });
}
if (utils.isNonBuiltinObject(valForKey) && pathtype === 'nested') {
$applyDefaultsToNested(path[key], prefix + key, this);
this.$set(prefix + key, path[key], constructing, Object.assign({}, options, { _skipMarkModified: true }));
continue;
} else if (strict) {
// Don't overwrite defaults with undefined keys (gh-3981) (gh-9039)
if (constructing && path[key] === void 0 &&
this.$get(pathName) !== void 0) {
continue;
}
if (pathtype === 'adhocOrUndefined') {
pathtype = getEmbeddedDiscriminatorPath(this, pathName, { typeOnly: true });
}
if (pathtype === 'real' || pathtype === 'virtual') {
const p = path[key];
this.$set(prefix + key, p, constructing, options);
} else if (pathtype === 'nested' && path[key] instanceof Document) {
this.$set(prefix + key,
path[key].toObject({ transform: false }), constructing, options);
} 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, options);
}
}
// Ensure all properties are in correct order by deleting and recreating every property.
for (const key of Object.keys(this.$__schema.tree)) {
if (this._doc.hasOwnProperty(key)) {
const val = this._doc[key];
delete this._doc[key];
this._doc[key] = val;
}
}
return this;
}
let pathType = this.$__schema.pathType(path);
if (pathType === 'adhocOrUndefined') {
pathType = getEmbeddedDiscriminatorPath(this, path, { typeOnly: true });
}
// Assume this is a Mongoose document that was copied into a POJO using
// `Object.assign()` or `{...doc}`
val = handleSpreadDoc(val);
// if this doc is being constructed we should not trigger getters
const priorVal = (() => {
if (this.$__.priorDoc != null) {
return this.$__.priorDoc.$__getValue(path);
}
if (constructing) {
return void 0;
}
return this.$__getValue(path);
})();
if (pathType === 'nested' && val) {
if (typeof val === 'object' && val != null) {
if (val.$__ != null) {
val = val.toObject(internalToObjectOptions);
}
if (val == null) {
this.invalidate(path, new MongooseError.CastError('Object', val, path));
return this;
}
const hasInitialVal = this.$__.savedState != null && this.$__.savedState.hasOwnProperty(path);
if (this.$__.savedState != null && !this.$isNew && !this.$__.savedState.hasOwnProperty(path)) {
const initialVal = this.$__getValue(path);
this.$__.savedState[path] = initialVal;
const keys = Object.keys(initialVal || {});
for (const key of keys) {
this.$__.savedState[path + '.' + key] = initialVal[key];
}
}
if (!merge) {
this.$__setValue(path, null);
cleanModifiedSubpaths(this, path);
} else {
return this.$set(val, path, constructing);
}
const keys = getKeysInSchemaOrder(this.$__schema, val, path);
this.$__setValue(path, {});
for (const key of keys) {
this.$set(path + '.' + key, val[key], constructing, options);
}
if (priorVal != null && utils.deepEqual(hasInitialVal ? this.$__.savedState[path] : priorVal, val)) {
this.unmarkModified(path);
} else {
this.markModified(path);
}
cleanModifiedSubpaths(this, path, { skipDocArrays: true });
return this;
}
this.invalidate(path, new MongooseError.CastError('Object', val, path));
return this;
}
let schema;
const parts = path.indexOf('.') === -1 ? [path] : path.split('.');
// Might need to change path for top-level alias
if (typeof this.$__schema.aliases[parts[0]] == 'string') {
parts[0] = this.$__schema.aliases[parts[0]];
}
if (pathType === 'adhocOrUndefined' && strict) {
// check for roots that are Mixed types
let mixed;
for (i = 0; i < parts.length; ++i) {
const subpath = parts.slice(0, i + 1).join('.');
// 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;
}
schema = this.$__schema.path(subpath);
if (schema == null) {
continue;
}
if (schema instanceof MixedSchema) {
// allow changes to sub paths of mixed types
mixed = true;
break;
}
}
if (schema == null) {
// Check for embedded discriminators
schema = getEmbeddedDiscriminatorPath(this, path);
}
if (!mixed && !schema) {
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);
}
// gh-4578, if setting a deeply nested path that doesn't exist yet, create it
let cur = this._doc;
let curPath = '';
for (i = 0; i < parts.length - 1; ++i) {
cur = cur[parts[i]];
curPath += (curPath.length > 0 ? '.' : '') + parts[i];
if (!cur) {
this.$set(curPath, {});
// Hack re: gh-5800. If nested field is not selected, it probably exists
// so `MongoServerError: cannot use the part (nested of nested.num) to
// traverse the element ({nested: null})` is not likely. If user gets
// that error, its their fault for now. We should reconsider disallowing
// modifying not selected paths for 6.x
if (!this.$__isSelected(curPath)) {
this.unmarkModified(curPath);
}
cur = this.$__getValue(curPath);
}
}
let 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) {
const subpath = parts.slice(0, i + 1).join('.');
if (this.$get(subpath, null, { getters: false }) === null) {
pathToMark = subpath;
break;
}
}
if (!pathToMark) {
pathToMark = path;
}
}
if (!schema) {
this.$__set(pathToMark, path, options, constructing, parts, schema, val, priorVal);
return this;
}
// If overwriting a subdocument path, make sure to clear out
// any errors _before_ setting, so new errors that happen
// get persisted. Re: #9080
if (schema.$isSingleNested || schema.$isMongooseArray) {
_markValidSubpaths(this, path);
}
if (schema.$isSingleNested && val != null && merge) {
if (val instanceof Document) {
val = val.toObject({ virtuals: false, transform: false });
}
const keys = Object.keys(val);
for (const key of keys) {
this.$set(path + '.' + key, val[key], constructing, options);
}
return this;
}
let 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
const refMatches = (() => {
if (schema.options == null) {
return false;
}
if (!(val instanceof Document)) {
return false;
}
const model = val.constructor;
// Check ref
const ref = schema.options.ref;
if (ref != null && (ref === model.modelName || ref === model.baseModelName)) {
return true;
}
// Check refPath
const refPath = schema.options.refPath;
if (refPath == null) {
return false;
}
const modelName = val.get(refPath);
return modelName === model.modelName || modelName === model.baseModelName;
})();
let didPopulate = false;
if (refMatches && val instanceof Document) {
this.$populated(path, val._id, { [populateModelSymbol]: val.constructor });
val.$__.wasPopulated = true;
didPopulate = true;
}
let popOpts;
if (schema.options &&
Array.isArray(schema.options[typeKey]) &&
schema.options[typeKey].length &&
schema.options[typeKey][0].ref &&
_isManuallyPopulatedArray(val, schema.options[typeKey][0].ref)) {
popOpts = { [populateModelSymbol]: val[0].constructor };
this.$populated(path, val.map(function(v) { return v._id; }), popOpts);
for (const doc of val) {
doc.$__.wasPopulated = true;
}
didPopulate = true;
}
if (this.$__schema.singleNestedPaths[path] == null && (!refMatches || !schema.$isSingleNested || !val.$__)) {
// If this path is underneath a single nested schema, we'll call the setter
// later in `$__set()` because we don't take `_doc` when we iterate through
// a single nested doc. That's to make sure we get the correct context.
// Otherwise we would double-call the setter, see gh-7196.
val = schema.applySetters(val, this, false, priorVal);
}
if (schema.$isMongooseDocumentArray &&
Array.isArray(val) &&
val.length > 0 &&
val[0] != null &&
val[0].$__ != null &&
val[0].$__.populated != null) {
const populatedPaths = Object.keys(val[0].$__.populated);
for (const populatedPath of populatedPaths) {
this.$populated(path + '.' + populatedPath,
val.map(v => v.$populated(populatedPath)),
val[0].$__.populated[populatedPath].options);
}
didPopulate = true;
}
if (!didPopulate && this.$__.populated) {
// If this array partially contains populated documents, convert them
// all to ObjectIds re: #8443
if (Array.isArray(val) && this.$__.populated[path]) {
for (let i = 0; i < val.length; ++i) {
if (val[i] instanceof Document) {
val.set(i, val[i]._id, true);
}
}
}
delete this.$__.populated[path];
}
if (schema.$isSingleNested && val != null) {
_checkImmutableSubpaths(val, schema, priorVal);
}
this.$markValid(path);
} catch (e) {
if (e instanceof MongooseError.StrictModeError && e.isImmutableError) {
this.invalidate(path, e);
} else if (e instanceof MongooseError.CastError) {
this.invalidate(e.path, e);
if (e.$originalErrorPath) {
this.invalidate(path,
new MongooseError.CastError(schema.instance, val, path, e.$originalErrorPath));
}
} else {
this.invalidate(path,
new MongooseError.CastError(schema.instance, val, path, e));
}
shouldSet = false;
}
if (shouldSet) {
const doc = this.$isSubdocument ? this.ownerDocument() : this;
const savedState = doc.$__.savedState;
const savedStatePath = this.$isSubdocument ? this.$__.fullPath + '.' + path : path;
if (savedState != null) {
const firstDot = savedStatePath.indexOf('.');
const topLevelPath = firstDot === -1 ? savedStatePath : savedStatePath.slice(0, firstDot);
if (!savedState.hasOwnProperty(topLevelPath)) {
savedState[topLevelPath] = utils.clone(doc.$__getValue(topLevelPath));
}
}
this.$__set(pathToMark, path, options, constructing, parts, schema, val, priorVal);
if (savedState != null && savedState.hasOwnProperty(savedStatePath) && utils.deepEqual(val, savedState[savedStatePath])) {
this.unmarkModified(path);
}
}
if (schema.$isSingleNested && (this.isDirectModified(path) || val == null)) {
cleanModifiedSubpaths(this, path);
}
return this;
};
/*!
* ignore
*/
function _isManuallyPopulatedArray(val, ref) {
if (!Array.isArray(val)) {
return false;
}
if (val.length === 0) {
return false;
}
for (const el of val) {
if (!(el instanceof Document)) {
return false;
}
const modelName = el.constructor.modelName;
if (modelName == null) {
return false;
}
if (el.constructor.modelName != ref && el.constructor.baseModelName != ref) {
return false;
}
}
return true;
}
/**
* 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
* @method set
* @memberOf Document
* @instance
*/
Document.prototype.set = Document.prototype.$set;
/**
* Determine if we should mark this change as modified.
*
* @return {Boolean}
* @api private
* @method $__shouldModify
* @memberOf Document
* @instance
*/
Document.prototype.$__shouldModify = function(pathToMark, path, options, constructing, parts, schema, val, priorVal) {
if (options._skipMarkModified) {
return false;
}
if (this.$isNew) {
return true;
}
// Re: the note about gh-7196, `val` is the raw value without casting or
// setters if the full path is under a single nested subdoc because we don't
// want to double run setters. So don't set it as modified. See gh-7264.
if (this.$__schema.singleNestedPaths[path] != null) {
return false;
}
if (val === void 0 && !this.$__isSelected(path)) {
// when a path is not selected in a query, its initial
// value will be undefined.
return true;
}
if (val === void 0 && 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 || utils.getValue(path, this))) {
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
* @instance
*/
Document.prototype.$__set = function(pathToMark, path, options, constructing, parts, schema, val, priorVal) {
Embedded = Embedded || require('./types/ArraySubdocument');
const shouldModify = this.$__shouldModify(pathToMark, path, options, constructing, parts,
schema, val, priorVal);
const _this = this;
if (shouldModify) {
this.markModified(pathToMark);
// handle directly setting arrays (gh-1126)
MongooseArray || (MongooseArray = require('./types/array'));
if (val && val.isMongooseArray) {
val._registerAtomic('$set', val);
// Update embedded document parent references (gh-5189)
if (val.isMongooseDocumentArray) {
val.forEach(function(item) {
item && item.__parentArray && (item.__parentArray = 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.startsWith(path + '.')) {
_this.$__.activePaths.ignore(modifiedPath);
}
});
}
} else if (Array.isArray(val) && val.isMongooseArray && Array.isArray(priorVal) && priorVal.isMongooseArray) {
val[arrayAtomicsSymbol] = priorVal[arrayAtomicsSymbol];
val[arrayAtomicsBackupSymbol] = priorVal[arrayAtomicsBackupSymbol];
}
let obj = this._doc;
let i = 0;
const l = parts.length;
let cur = '';
for (; i < l; i++) {
const next = i + 1;
const last = next === l;
cur += (cur ? '.' + parts[i] : parts[i]);
if (specialProperties.has(parts[i])) {
return;
}
if (last) {
if (obj instanceof Map) {
obj.set(parts[i], val);
} else {
obj[parts[i]] = val;
}
} else {
if (utils.isPOJO(obj[parts[i]])) {
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 {
obj[parts[i]] = obj[parts[i]] || {};
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
* @param {Object} [options]
* @param {Boolean} [options.virtuals=false] Apply virtuals before getting this path
* @param {Boolean} [options.getters=true] If false, skip applying getters and just get the raw value
* @api public
*/
Document.prototype.get = function(path, type, options) {
let adhoc;
options = options || {};
if (type) {
adhoc = this.$__schema.interpretAsType(path, type, this.$__schema.options);
}
let schema = this.$__path(path);
if (schema == null) {
schema = this.$__schema.virtualpath(path);
}
if (schema instanceof MixedSchema) {
const virtual = this.$__schema.virtualpath(path);
if (virtual != null) {
schema = virtual;
}
}
const pieces = path.indexOf('.') === -1 ? [path] : path.split('.');
let obj = this._doc;
if (schema instanceof VirtualType) {
return schema.applyGetters(void 0, this);
}
// Might need to change path for top-level alias
if (typeof this.$__schema.aliases[pieces[0]] == 'string') {
pieces[0] = this.$__schema.aliases[pieces[0]];
}
for (let i = 0, l = pieces.length; i < l; i++) {
if (obj && obj._doc) {
obj = obj._doc;
}
if (obj == null) {
obj = void 0;
} else if (obj instanceof Map) {
obj = obj.get(pieces[i], { getters: false });
} else if (i === l - 1) {
obj = utils.getValue(pieces[i], obj);
} else {
obj = obj[pieces[i]];
}
}
if (adhoc) {
obj = adhoc.cast(obj);
}
if (schema != null && options.getters !== false) {
obj = schema.applyGetters(obj, this);
} else if (this.$__schema.nested[path] && options.virtuals) {
// Might need to apply virtuals if this is a nested path
return applyVirtuals(this, utils.clone(obj) || {}, { path: path });
}
return obj;
};
/*!
* ignore
*/
Document.prototype[getSymbol] = Document.prototype.get;
Document.prototype.$get = Document.prototype.get;
/**
* Returns the schematype for the given `path`.
*
* @param {String} path
* @api private
* @method $__path
* @memberOf Document
* @instance
*/
Document.proto