mongoose
Version:
Mongoose MongoDB ODM
1,875 lines (1,641 loc) • 100 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 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 get = require('./helpers/get');
const getEmbeddedDiscriminatorPath = require('./helpers/document/getEmbeddedDiscriminatorPath');
const idGetter = require('./plugins/idGetter');
const isDefiningProjection = require('./helpers/projection/isDefiningProjection');
const isExclusive = require('./helpers/projection/isExclusive');
const inspect = require('util').inspect;
const internalToObjectOptions = require('./options').internalToObjectOptions;
const mpath = require('mpath');
const utils = require('./utils');
const clone = utils.clone;
const deepEqual = utils.deepEqual;
const isMongooseObject = utils.isMongooseObject;
const arrayAtomicsSymbol = require('./helpers/symbols').arrayAtomicsSymbol;
const documentArrayParent = require('./helpers/symbols').documentArrayParent;
const documentSchemaSymbol = require('./helpers/symbols').documentSchemaSymbol;
const getSymbol = require('./helpers/symbols').getSymbol;
const populateModelSymbol = require('./helpers/symbols').populateModelSymbol;
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 {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, options) {
if (typeof skipId === 'object' && skipId != null) {
options = skipId;
skipId = options.skipId;
}
options = 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;
this.errors = undefined;
this.$__.$options = options || {};
if (obj != null && typeof obj !== 'object') {
throw new ObjectParameterError(obj, 'obj', 'Document');
}
const schema = this.schema;
if (typeof fields === 'boolean') {
this.$__.strictMode = fields;
fields = undefined;
} else {
this.$__.strictMode = schema.options.strict;
this.$__.selected = fields;
}
const required = schema.requiredPaths(true);
for (let i = 0; i < required.length; ++i) {
this.$__.activePaths.require(required[i]);
}
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
$__applyDefaults(this, fields, skipId, exclude, hasIncludedChildren, true, {
isNew: this.isNew
});
}
if (obj) {
if (obj instanceof Document) {
this.isNew = obj.isNew;
}
// Skip set hooks
if (this.$__original_set) {
this.$__original_set(obj, undefined, true);
} else {
this.$set(obj, undefined, true);
}
}
// 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) {
EventEmitter.prototype.once.call(this, 'init', () => {
$__applyDefaults(this, fields, skipId, exclude, hasIncludedChildren, false, options.skipDefaults, {
isNew: this.isNew
});
});
} else {
$__applyDefaults(this, fields, skipId, exclude, hasIncludedChildren, false, options.skipDefaults, {
isNew: this.isNew
});
}
this.$__._id = this._id;
this.$locals = {};
if (!schema.options.strict && obj) {
const _this = this;
const keys = Object.keys(this._doc);
keys.forEach(function(key) {
if (!(key in schema.tree)) {
defineKey(key, null, _this);
}
});
}
applyQueue(this);
}
/*!
* 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;
for (const i in EventEmitter.prototype) {
Document[i] = EventEmitter.prototype[i];
}
/**
* The documents 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,
writable: true
});
/**
* Boolean flag specifying if the document is new.
*
* @api public
* @property isNew
* @memberOf Document
* @instance
*/
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
* @memberOf Document
* @instance
*/
Document.prototype.id;
/**
* Hash containing current validation errors.
*
* @api public
* @property errors
* @memberOf Document
* @instance
*/
Document.prototype.errors;
/*!
* ignore
*/
function $__hasIncludedChildren(fields) {
const hasIncludedChildren = {};
const keys = Object.keys(fields);
for (let j = 0; j < keys.length; ++j) {
const parts = keys[j].split('.');
const c = [];
for (let k = 0; k < parts.length; ++k) {
c.push(parts[k]);
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 = p.split('.');
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;
}
def = type.getDefault(doc, false);
if (typeof def !== 'undefined') {
doc_[piece] = def;
doc.$__.activePaths.default(p);
}
} else if (included) {
// selected field
def = type.getDefault(doc, false);
if (typeof def !== 'undefined') {
doc_[piece] = def;
doc.$__.activePaths.default(p);
}
}
} else {
def = type.getDefault(doc, false);
if (typeof def !== 'undefined') {
doc_[piece] = def;
doc.$__.activePaths.default(p);
}
}
} else {
doc_ = doc_[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 = p.split('.');
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;
};
/*!
* ignore
*/
Document.prototype.$__init = function(doc, opts) {
this.isNew = false;
this.$init = true;
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 (let i = 0; i < opts.populated.length; ++i) {
const 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, opts);
markArraySubdocsPopulated(this, opts.populated);
this.emit('init', this);
this.constructor.emit('init', this);
this.$__._id = this._id;
return this;
};
/*!
* If populating a path within a document array, make sure each
* subdoc within the array knows its subpaths are populated.
*
* ####Example:
* const doc = await Article.findOne().populate('comments.author');
* doc.comments[0].populated('author'); // Should be set
*/
function markArraySubdocsPopulated(doc, populated) {
if (doc._id == null || populated == null || populated.length === 0) {
return;
}
const id = String(doc._id);
for (const item of populated) {
if (item.isVirtual) {
continue;
}
const path = item.path;
const pieces = path.split('.');
for (let i = 0; i < pieces.length - 1; ++i) {
const subpath = pieces.slice(0, i + 1).join('.');
const rest = pieces.slice(i + 1).join('.');
const val = doc.get(subpath);
if (val == null) {
continue;
}
if (val.isMongooseDocumentArray) {
for (let j = 0; j < val.length; ++j) {
val[j].populated(rest, item._docs[id][j], item);
}
break;
}
}
}
}
/*!
* 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;
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];
} else {
if (obj[i] === null) {
doc[i] = 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
}));
}
} 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
* @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](#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) {
return this.$__.session;
}
this.$__.session = session;
if (!this.ownerDocument) {
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;
}
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;
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 (typeof path !== 'string') {
// new Document({ key: val })
if (path === null || path === void 0) {
const _ = path;
path = val;
val = _;
} else {
prefix = val ? val + '.' : '';
if (path instanceof Document) {
if (path.$__isNested) {
path = path.toObject();
} else {
path = path._doc;
}
}
keys = Object.keys(path);
const len = keys.length;
if (len === 0 && !this.schema.options.minimize) {
if (val) {
this.$set(val, {});
}
return this;
}
while (i < len) {
_handleIndex.call(this, i++);
}
return this;
}
} else {
this.$__.$setCalled.add(path);
}
function _handleIndex(i) {
key = keys[i];
const pathName = prefix + key;
pathtype = this.schema.pathType(pathName);
// 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 &&
Object.keys(this._doc[key]).length === 0) {
delete this._doc[key];
}
if (typeof path[key] === 'object' &&
!utils.isNativeObject(path[key]) &&
!utils.isMongooseType(path[key]) &&
path[key] != null &&
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.$__.$setCalled.add(prefix + key);
this.$set(path[key], prefix + key, constructing, options);
} 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 === 'adhocOrUndefined') {
pathtype = getEmbeddedDiscriminatorPath(this, pathName, { typeOnly: true });
}
if (pathtype === 'real' || pathtype === 'virtual') {
// Check for setting single embedded schema to document (gh-3535)
let p = path[key];
if (this.schema.paths[pathName] &&
this.schema.paths[pathName].$isSingleNested &&
path[key] instanceof Document) {
p = p.toObject({ virtuals: false, transform: false });
}
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);
}
}
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}`
if (utils.isPOJO(val) && val.$__ != null && val._doc != null) {
val = val._doc;
}
if (pathType === 'nested' && val) {
if (typeof val === 'object' && val != null) {
if (!merge) {
this.$__setValue(path, null);
cleanModifiedSubpaths(this, path);
} else {
return this.$set(val, path, constructing);
}
const keys = Object.keys(val);
this.$__setValue(path, {});
for (const key of keys) {
this.$set(path + '.' + key, val[key], constructing);
}
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.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 `MongoError: 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 this doc is being constructed we should not trigger getters
const priorVal = (() => {
if (this.$__.$options.priorDoc != null) {
return this.$__.$options.priorDoc.$__getValue(path);
}
if (constructing) {
return void 0;
}
return this.$__getValue(path);
})();
if (!schema) {
this.$__set(pathToMark, path, constructing, parts, schema, val, priorVal);
return this;
}
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);
if (modelName === model.modelName || modelName === model.baseModelName) {
return true;
}
return false;
})();
let didPopulate = false;
if (refMatches && val instanceof Document) {
this.populated(path, val._id, { [populateModelSymbol]: val.constructor });
didPopulate = true;
}
let popOpts;
if (schema.options &&
Array.isArray(schema.options[this.schema.options.typeKey]) &&
schema.options[this.schema.options.typeKey].length &&
schema.options[this.schema.options.typeKey][0].ref &&
_isManuallyPopulatedArray(val, schema.options[this.schema.options.typeKey][0].ref)) {
if (this.ownerDocument) {
popOpts = { [populateModelSymbol]: val[0].constructor };
this.ownerDocument().populated(this.$__fullPath(path),
val.map(function(v) { return v._id; }), popOpts);
} else {
popOpts = { [populateModelSymbol]: val[0].constructor };
this.populated(path, val.map(function(v) { return v._id; }), popOpts);
}
didPopulate = true;
}
if (this.schema.singleNestedPaths[path] == null) {
// 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[i] = val[i]._id;
}
}
}
delete this.$__.populated[path];
}
this.$markValid(path);
} catch (e) {
if (e instanceof MongooseError.StrictModeError && e.isImmutableError) {
this.invalidate(path, e);
} else {
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) || 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, constructing, parts, schema, val, priorVal) {
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 || 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
* @instance
*/
Document.prototype.$__set = function(pathToMark, path, constructing, parts, schema, val, priorVal) {
Embedded = Embedded || require('./types/embedded');
const shouldModify = this.$__shouldModify(pathToMark, path, 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);
}
});
}
}
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.split('.');
let obj = this._doc;
if (schema instanceof VirtualType) {
if (schema.getters.length === 0) {
return void 0;
}
return schema.applyGetters(null, 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]);
} 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;
/**
* Returns the schematype for the given `path`.
*
* @param {String} path
* @api private
* @method $__path
* @memberOf Document
* @instance
*/
Document.prototype.$__path = function(path) {
const adhocs = this.$__.adhocPaths;
const adhocType = adhocs && adhocs.hasOwnProperty(path) ? adhocs[path] : null;
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
* @param {Document} [scope] the scope to run validators with
* @api public
*/
Document.prototype.markModified = function(path, scope) {
this.$__.activePaths.modify(path);
if (scope != null && !this.ownerDocument) {
this.$__.pathsToScopes[path] = scope;
}
};
/**
* 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);
delete this.$__.pathsToScopes[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
*
* @memberOf Document
* @instance
* @method $ignore
* @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 directly modified. A direct
* modified path is a path that you explicitly set, whether via `doc.foo = 'bar'`,
* `Object.assign(doc, { foo: 'bar' })`, or `doc.set('foo', 'bar')`.
*
* A path `a` may be in `modifiedPaths()` but not in `directModifiedPaths()`
* because a child of `a` was directly modified.
*
* ####Example
* const schema = new Schema({ foo: String, nested: { bar: String } });
* const Model = mongoose.model('Test', schema);
* await Model.create({ foo: 'original', nested: { bar: 'original' } });
*
* const doc = await Model.findOne();
* doc.nested.bar = 'modified';
* doc.directModifiedPaths(); // ['nested.bar']
* doc.modifiedPaths(); // ['nested', 'nested.bar']
*
* @return {Array}
* @api public
*/
Document.prototype.directModifiedPaths = function() {
return Object.keys(this.$__.activePaths.states.modify);
};
/**
* Returns true if the given path is nullish or only contains empty objects.
* Useful for determining whether this subdoc will get stripped out by the
* [minimize option](/docs/guide.html#minimize).
*
* ####Example:
* const schema = new Schema({ nested: { foo: String } });
* const Model = mongoose.model('Test', schema);
* const doc = new Model({});
* doc.$isEmpty('nested'); // true
* doc.nested.$isEmpty(); // true
*
* doc.nested.foo = 'bar';
* doc.$isEmpty('nested'); // false
* doc.nested.$isEmpty(); // false
*
* @memberOf Document
* @instance
* @api public
* @method $isEmpty
* @return {Boolean}
*/
Document.prototype.$isEmpty = function(path) {
const isEmptyOptions = {
minimize: true,
virtuals: false,
getters: false,
transform: false
};
if (arguments.length > 0) {
const v = this.get(path);
if (v == null) {
return true;
}
if (typeof v !== 'object') {
return false;
}
if (utils.isPOJO(v)) {
return _isEmpty(v);
}
return Object.keys(v.toObject(isEmptyOptions)).length === 0;
}
return Object.keys(this.toObject(isEmptyOptions)).length === 0;
};
function _isEmpty(v) {
if (v == null) {
return true;
}
if (typeof v !== 'object' || Array.isArray(v)) {
return false;
}
for (const key of Object.keys(v)) {
if (!_isEmpty(v[key])) {
return false;
}
}
return true;
}
/**
* Returns the list of paths that have been modified.
*
* @param {Object} [options]
* @param {Boolean} [options.includeChildren=false] if true, returns children of modified paths as well. For example, if false, the list of modified paths for `doc.colors = { primary: 'blue' };` will **not** contain `colors.primary`. If true, `modifiedPaths()` will return an array that contains `colors.primary`.
* @return {Array}
* @api public
*/
Document.prototype.modifiedPaths = function(options) {
options = options || {};
const directModifiedPaths = Object.keys(this.$__.activePaths.states.modify);
const _this = this;
return directModifiedPaths.reduce(function(list, path) {
const parts = path.split('.');
list = 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);
}));
if (!options.includeChildren) {
return list;
}
let cur = _this.get(path);
if (cur != null && typeof cur === 'object') {
if (cur._doc) {
cur = cur._doc;
}
if (Array.isArray(cur)) {
const len = cur.length;
for (let i = 0; i < len; ++i) {
if (list.indexOf(path + '.' + i) === -1) {
list.push(path + '.' + i);
if (cur[i] != null && cur[i].$__) {
const modified = cur[i].modifiedPaths();
for (const childPath of modified) {
list.push(path + '.' + i + '.' + childPath);
}
}
}
}
} else {
Object.keys(cur).
filter(function(key) {
return list.indexOf(path + '.' + key) === -1;
}).
forEach(function(key) {
list.push(path + '.' + key);
});
}
}
return list;
}, []);
};
/**
* 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, modifiedPaths) {
if (paths) {
if (!Array.isArray(paths)) {
paths = paths.split(' ');
}
const modified = modifiedPaths || this.modifiedPaths();
const directModifiedPaths = Object.keys(this.$__.activePaths.states.modify);
const isModifiedChild = paths.some(function(path) {
return !!~modified.indexOf(path);
});
return isModifiedChild || paths.some(function(path) {
return directModifiedPaths.some(function(mod) {
return mod === path || path.startsWith(mod + '.');
});
});
}
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
*
* @memberOf Document
* @instance
* @method $isDefault
* @param {String} [path]
* @return {Boolean}
* @api public
*/
Document.prototype.$isDefault = function(path) {
return (path in this.$__.activePaths.states.default);
};
/**
* Getter/setter, determines whether the document was removed or not.
*
* ####Example:
* product.remove(function (err, product) {
* product.$isDeleted(); // true
* product.remove(); // no-op, doesn't send anything to the db
*
* product.$isDeleted(false);
* product.$isDeleted(); // false
* product.remove(); // will execute a remove against the db
* })
*
* @param {Boolean} [val] optional, overrides whether mongoose thinks the doc is deleted
* @return {Boolean} whether mongoose thinks this doc is deleted.
* @method $isDeleted
* @memberOf Document
* @instance
* @api public
*/
Document.prototype.$isDeleted = function(val) {
if (arguments.length === 0) {
return !!this.$__.isDeleted;
}
this.$__.isDeleted = !!val;
return this;
};
/**
* 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 i