12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160 |
- 'use strict';
- if (global.MONGOOSE_DRIVER_PATH) {
- const deprecationWarning = 'The `MONGOOSE_DRIVER_PATH` global property is ' +
- 'deprecated. Use `mongoose.driver.set()` instead.';
- const setDriver = require('util').deprecate(function() {
- require('./driver').set(require(global.MONGOOSE_DRIVER_PATH));
- }, deprecationWarning);
- setDriver();
- } else {
- require('./driver').set(require('./drivers/node-mongodb-native'));
- }
- const Document = require('./document');
- const EventEmitter = require('events').EventEmitter;
- const Schema = require('./schema');
- const SchemaType = require('./schematype');
- const SchemaTypes = require('./schema/index');
- const VirtualType = require('./virtualtype');
- const STATES = require('./connectionstate');
- const VALID_OPTIONS = require('./validoptions');
- const Types = require('./types');
- const Query = require('./query');
- const Model = require('./model');
- const applyPlugins = require('./helpers/schema/applyPlugins');
- const driver = require('./driver');
- const get = require('./helpers/get');
- const promiseOrCallback = require('./helpers/promiseOrCallback');
- const legacyPluralize = require('mongoose-legacy-pluralize');
- const utils = require('./utils');
- const pkg = require('../package.json');
- const cast = require('./cast');
- const removeSubdocs = require('./plugins/removeSubdocs');
- const saveSubdocs = require('./plugins/saveSubdocs');
- const trackTransaction = require('./plugins/trackTransaction');
- const validateBeforeSave = require('./plugins/validateBeforeSave');
- const Aggregate = require('./aggregate');
- const PromiseProvider = require('./promise_provider');
- const shardingPlugin = require('./plugins/sharding');
- const defaultMongooseSymbol = Symbol.for('mongoose:default');
- require('./helpers/printJestWarning');
- function Mongoose(options) {
- this.connections = [];
- this.models = {};
- this.modelSchemas = {};
- this.events = new EventEmitter();
-
- this.options = Object.assign({
- pluralization: true,
- autoIndex: true,
- useCreateIndex: false
- }, options);
- const conn = this.createConnection();
- conn.models = this.models;
- if (this.options.pluralization) {
- this._pluralize = legacyPluralize;
- }
-
-
- if (!options || !options[defaultMongooseSymbol]) {
- const _this = this;
- this.Schema = function() {
- this.base = _this;
- return Schema.apply(this, arguments);
- };
- this.Schema.prototype = Object.create(Schema.prototype);
- Object.assign(this.Schema, Schema);
- this.Schema.base = this;
- this.Schema.Types = Object.assign({}, Schema.Types);
- } else {
-
-
-
- for (const key of ['Schema', 'model']) {
- this[key] = Mongoose.prototype[key];
- }
- }
- this.Schema.prototype.base = this;
- Object.defineProperty(this, 'plugins', {
- configurable: false,
- enumerable: true,
- writable: false,
- value: [
- [saveSubdocs, { deduplicate: true }],
- [validateBeforeSave, { deduplicate: true }],
- [shardingPlugin, { deduplicate: true }],
- [removeSubdocs, { deduplicate: true }],
- [trackTransaction, { deduplicate: true }]
- ]
- });
- }
- Mongoose.prototype.cast = cast;
- Mongoose.prototype.STATES = STATES;
- Mongoose.prototype.driver = driver;
- Mongoose.prototype.set = function(key, value) {
- const _mongoose = this instanceof Mongoose ? this : mongoose;
- if (VALID_OPTIONS.indexOf(key) === -1) throw new Error(`\`${key}\` is an invalid option.`);
- if (arguments.length === 1) {
- return _mongoose.options[key];
- }
- _mongoose.options[key] = value;
- if (key === 'objectIdGetter') {
- if (value) {
- Object.defineProperty(mongoose.Types.ObjectId.prototype, '_id', {
- enumerable: false,
- configurable: true,
- get: function() {
- return this;
- }
- });
- } else {
- delete mongoose.Types.ObjectId.prototype._id;
- }
- }
- return _mongoose;
- };
- Mongoose.prototype.get = Mongoose.prototype.set;
- Mongoose.prototype.createConnection = function(uri, options, callback) {
- const _mongoose = this instanceof Mongoose ? this : mongoose;
- const conn = new Connection(_mongoose);
- if (typeof options === 'function') {
- callback = options;
- options = null;
- }
- _mongoose.connections.push(conn);
- _mongoose.events.emit('createConnection', conn);
- if (arguments.length > 0) {
- return conn.openUri(uri, options, callback);
- }
- return conn;
- };
- Mongoose.prototype.connect = function(uri, options, callback) {
- const _mongoose = this instanceof Mongoose ? this : mongoose;
- const conn = _mongoose.connection;
- return _mongoose._promiseOrCallback(callback, cb => {
- conn.openUri(uri, options, err => {
- if (err != null) {
- return cb(err);
- }
- return cb(null, _mongoose);
- });
- });
- };
- Mongoose.prototype.disconnect = function(callback) {
- const _mongoose = this instanceof Mongoose ? this : mongoose;
- return _mongoose._promiseOrCallback(callback, cb => {
- let remaining = _mongoose.connections.length;
- if (remaining <= 0) {
- return cb(null);
- }
- _mongoose.connections.forEach(conn => {
- conn.close(function(error) {
- if (error) {
- return cb(error);
- }
- if (!--remaining) {
- cb(null);
- }
- });
- });
- });
- };
- Mongoose.prototype.startSession = function() {
- const _mongoose = this instanceof Mongoose ? this : mongoose;
- return _mongoose.connection.startSession.apply(_mongoose.connection, arguments);
- };
- Mongoose.prototype.pluralize = function(fn) {
- const _mongoose = this instanceof Mongoose ? this : mongoose;
- if (arguments.length > 0) {
- _mongoose._pluralize = fn;
- }
- return _mongoose._pluralize;
- };
- Mongoose.prototype.model = function(name, schema, collection, skipInit) {
- const _mongoose = this instanceof Mongoose ? this : mongoose;
- let model;
- if (typeof name === 'function') {
- model = name;
- name = model.name;
- if (!(model.prototype instanceof Model)) {
- throw new _mongoose.Error('The provided class ' + name + ' must extend Model');
- }
- }
- if (typeof schema === 'string') {
- collection = schema;
- schema = false;
- }
- if (utils.isObject(schema) && !(schema instanceof Schema)) {
- schema = new Schema(schema);
- }
- if (schema && !(schema instanceof Schema)) {
- throw new Error('The 2nd parameter to `mongoose.model()` should be a ' +
- 'schema or a POJO');
- }
- if (typeof collection === 'boolean') {
- skipInit = collection;
- collection = null;
- }
-
- let options;
- if (skipInit && utils.isObject(skipInit)) {
- options = skipInit;
- skipInit = true;
- } else {
- options = {};
- }
-
- if (!_mongoose.modelSchemas[name]) {
- if (schema) {
-
- _mongoose.modelSchemas[name] = schema;
- } else {
- throw new mongoose.Error.MissingSchemaError(name);
- }
- }
- const originalSchema = schema;
- if (schema) {
- if (_mongoose.get('cloneSchemas')) {
- schema = schema.clone();
- }
- _mongoose._applyPlugins(schema);
- }
- let sub;
-
-
- const overwriteModels = _mongoose.options.hasOwnProperty('overwriteModels') ?
- _mongoose.options.overwriteModels :
- options.overwriteModels;
- if (_mongoose.models[name] && options.cache !== false && overwriteModels !== true) {
- if (originalSchema &&
- originalSchema.instanceOfSchema &&
- originalSchema !== _mongoose.models[name].schema) {
- throw new _mongoose.Error.OverwriteModelError(name);
- }
- if (collection && collection !== _mongoose.models[name].collection.name) {
-
- model = _mongoose.models[name];
- schema = model.prototype.schema;
- sub = model.__subclass(_mongoose.connection, schema, collection);
-
- return sub;
- }
- return _mongoose.models[name];
- }
-
- if (!schema) {
- schema = this.modelSchemas[name];
- if (!schema) {
- throw new mongoose.Error.MissingSchemaError(name);
- }
- }
-
- if (!('pluralization' in schema.options)) {
- schema.options.pluralization = _mongoose.options.pluralization;
- }
- if (!collection) {
- collection = schema.get('collection') ||
- utils.toCollectionName(name, _mongoose.pluralize());
- }
- const connection = options.connection || _mongoose.connection;
- model = _mongoose.Model.compile(model || name, schema, collection, connection, _mongoose);
- if (!skipInit) {
-
- model.init(function $modelInitNoop() {});
- }
- connection.emit('model', model);
- if (options.cache === false) {
- return model;
- }
- _mongoose.models[name] = model;
- return _mongoose.models[name];
- };
- Mongoose.prototype.deleteModel = function(name) {
- const _mongoose = this instanceof Mongoose ? this : mongoose;
- _mongoose.connection.deleteModel(name);
- return _mongoose;
- };
- Mongoose.prototype.modelNames = function() {
- const _mongoose = this instanceof Mongoose ? this : mongoose;
- const names = Object.keys(_mongoose.models);
- return names;
- };
- Mongoose.prototype._applyPlugins = function(schema, options) {
- const _mongoose = this instanceof Mongoose ? this : mongoose;
- options = options || {};
- options.applyPluginsToDiscriminators = get(_mongoose,
- 'options.applyPluginsToDiscriminators', false);
- options.applyPluginsToChildSchemas = get(_mongoose,
- 'options.applyPluginsToChildSchemas', true);
- applyPlugins(schema, _mongoose.plugins, options, '$globalPluginsApplied');
- };
- Mongoose.prototype.plugin = function(fn, opts) {
- const _mongoose = this instanceof Mongoose ? this : mongoose;
- _mongoose.plugins.push([fn, opts]);
- return _mongoose;
- };
- Mongoose.prototype.__defineGetter__('connection', function() {
- return this.connections[0];
- });
- Mongoose.prototype.__defineSetter__('connection', function(v) {
- if (v instanceof Connection) {
- this.connections[0] = v;
- this.models = v.models;
- }
- });
- Mongoose.prototype.connections;
- const Connection = driver.get().getConnection();
- const Collection = driver.get().Collection;
- Mongoose.prototype.Aggregate = Aggregate;
- Mongoose.prototype.Collection = Collection;
- Mongoose.prototype.Connection = Connection;
- Mongoose.prototype.version = pkg.version;
- Mongoose.prototype.Mongoose = Mongoose;
- Mongoose.prototype.Schema = Schema;
- Mongoose.prototype.SchemaType = SchemaType;
- Mongoose.prototype.SchemaTypes = Schema.Types;
- Mongoose.prototype.VirtualType = VirtualType;
- Mongoose.prototype.Types = Types;
- Mongoose.prototype.Query = Query;
- Object.defineProperty(Mongoose.prototype, 'Promise', {
- get: function() {
- return PromiseProvider.get();
- },
- set: function(lib) {
- PromiseProvider.set(lib);
- }
- });
- Mongoose.prototype.PromiseProvider = PromiseProvider;
- Mongoose.prototype.Model = Model;
- Mongoose.prototype.Document = Document;
- Mongoose.prototype.DocumentProvider = require('./document_provider');
- Mongoose.prototype.ObjectId = SchemaTypes.ObjectId;
- Mongoose.prototype.isValidObjectId = function(v) {
- if (v == null) {
- return true;
- }
- const base = this || mongoose;
- const ObjectId = base.driver.get().ObjectId;
- if (v instanceof ObjectId) {
- return true;
- }
- if (v._id != null) {
- if (v._id instanceof ObjectId) {
- return true;
- }
- if (v._id.toString instanceof Function) {
- v = v._id.toString();
- if (typeof v === 'string' && v.length === 12) {
- return true;
- }
- if (typeof v === 'string' && v.length === 24 && /^[a-f0-9]*$/.test(v)) {
- return true;
- }
- return false;
- }
- }
- if (v.toString instanceof Function) {
- v = v.toString();
- }
- if (typeof v === 'string' && v.length === 12) {
- return true;
- }
- if (typeof v === 'string' && v.length === 24 && /^[a-f0-9]*$/.test(v)) {
- return true;
- }
- return false;
- };
- Mongoose.prototype.Decimal128 = SchemaTypes.Decimal128;
- Mongoose.prototype.Mixed = SchemaTypes.Mixed;
- Mongoose.prototype.Date = SchemaTypes.Date;
- Mongoose.prototype.Number = SchemaTypes.Number;
- Mongoose.prototype.Error = require('./error/index');
- Mongoose.prototype.now = function now() { return new Date(); };
- Mongoose.prototype.CastError = require('./error/cast');
- Mongoose.prototype.SchemaTypeOptions = require('./options/SchemaTypeOptions');
- Mongoose.prototype.mongo = require('mongodb');
- Mongoose.prototype.mquery = require('mquery');
- Mongoose.prototype._promiseOrCallback = function(callback, fn, ee) {
- return promiseOrCallback(callback, fn, ee, this.Promise);
- };
- const mongoose = module.exports = exports = new Mongoose({
- [defaultMongooseSymbol]: true
- });
|