You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

3335 lines
94 KiB

  1. /*!
  2. * Module dependencies.
  3. */
  4. var Document = require('./document');
  5. var MongooseError = require('./error');
  6. var VersionError = MongooseError.VersionError;
  7. var DivergentArrayError = MongooseError.DivergentArrayError;
  8. var Query = require('./query');
  9. var Aggregate = require('./aggregate');
  10. var Schema = require('./schema');
  11. var utils = require('./utils');
  12. var hasOwnProperty = utils.object.hasOwnProperty;
  13. var isMongooseObject = utils.isMongooseObject;
  14. var EventEmitter = require('events').EventEmitter;
  15. var util = require('util');
  16. var tick = utils.tick;
  17. var async = require('async');
  18. var PromiseProvider = require('./promise_provider');
  19. var VERSION_WHERE = 1,
  20. VERSION_INC = 2,
  21. VERSION_ALL = VERSION_WHERE | VERSION_INC;
  22. /**
  23. * Model constructor
  24. *
  25. * Provides the interface to MongoDB collections as well as creates document instances.
  26. *
  27. * @param {Object} doc values with which to create the document
  28. * @inherits Document http://mongoosejs.com/docs/api.html#document-js
  29. * @event `error`: If listening to this event, it is emitted when a document was saved without passing a callback and an `error` occurred. If not listening, the event bubbles to the connection used to create this Model.
  30. * @event `index`: Emitted after `Model#ensureIndexes` completes. If an error occurred it is passed with the event.
  31. * @event `index-single-start`: Emitted when an individual index starts within `Model#ensureIndexes`. The fields and options being used to build the index are also passed with the event.
  32. * @event `index-single-done`: Emitted when an individual index finishes within `Model#ensureIndexes`. If an error occurred it is passed with the event. The fields, options, and index name are also passed.
  33. * @api public
  34. */
  35. function Model(doc, fields, skipId) {
  36. Document.call(this, doc, fields, skipId);
  37. }
  38. /*!
  39. * Inherits from Document.
  40. *
  41. * All Model.prototype features are available on
  42. * top level (non-sub) documents.
  43. */
  44. Model.prototype.__proto__ = Document.prototype;
  45. /**
  46. * Connection the model uses.
  47. *
  48. * @api public
  49. * @property db
  50. */
  51. Model.prototype.db;
  52. /**
  53. * Collection the model uses.
  54. *
  55. * @api public
  56. * @property collection
  57. */
  58. Model.prototype.collection;
  59. /**
  60. * The name of the model
  61. *
  62. * @api public
  63. * @property modelName
  64. */
  65. Model.prototype.modelName;
  66. /**
  67. * If this is a discriminator model, `baseModelName` is the name of
  68. * the base model.
  69. *
  70. * @api public
  71. * @property baseModelName
  72. */
  73. Model.prototype.baseModelName;
  74. Model.prototype.$__handleSave = function(options, callback) {
  75. var _this = this;
  76. if (!options.safe && this.schema.options.safe) {
  77. options.safe = this.schema.options.safe;
  78. }
  79. if (typeof options.safe === 'boolean') {
  80. options.safe = null;
  81. }
  82. if (this.isNew) {
  83. // send entire doc
  84. var toObjectOptions = {};
  85. if (this.schema.options.toObject &&
  86. this.schema.options.toObject.retainKeyOrder) {
  87. toObjectOptions.retainKeyOrder = true;
  88. }
  89. toObjectOptions.depopulate = 1;
  90. toObjectOptions._skipDepopulateTopLevel = true;
  91. toObjectOptions.transform = false;
  92. var obj = this.toObject(toObjectOptions);
  93. if (!utils.object.hasOwnProperty(obj || {}, '_id')) {
  94. // documents must have an _id else mongoose won't know
  95. // what to update later if more changes are made. the user
  96. // wouldn't know what _id was generated by mongodb either
  97. // nor would the ObjectId generated my mongodb necessarily
  98. // match the schema definition.
  99. setTimeout(function() {
  100. callback(new Error('document must have an _id before saving'));
  101. }, 0);
  102. return;
  103. }
  104. this.$__version(true, obj);
  105. this.collection.insert(obj, options.safe, function(err, ret) {
  106. if (err) {
  107. _this.isNew = true;
  108. _this.emit('isNew', true);
  109. callback(err);
  110. return;
  111. }
  112. callback(null, ret);
  113. });
  114. this.$__reset();
  115. this.isNew = false;
  116. this.emit('isNew', false);
  117. // Make it possible to retry the insert
  118. this.$__.inserting = true;
  119. } else {
  120. // Make sure we don't treat it as a new object on error,
  121. // since it already exists
  122. this.$__.inserting = false;
  123. var delta = this.$__delta();
  124. if (delta) {
  125. if (delta instanceof Error) {
  126. callback(delta);
  127. return;
  128. }
  129. var where = this.$__where(delta[0]);
  130. if (where instanceof Error) {
  131. callback(where);
  132. return;
  133. }
  134. this.collection.update(where, delta[1], options.safe, function(err, ret) {
  135. if (err) {
  136. callback(err);
  137. return;
  138. }
  139. callback(null, ret);
  140. });
  141. } else {
  142. this.$__reset();
  143. callback();
  144. return;
  145. }
  146. this.emit('isNew', false);
  147. }
  148. };
  149. /*!
  150. * ignore
  151. */
  152. Model.prototype.$__save = function(options, callback) {
  153. var _this = this;
  154. _this.$__handleSave(options, function(error, result) {
  155. if (error) {
  156. return _this.schema.s.hooks.execPost('save:error', _this, [_this], { error: error }, function(error) {
  157. callback(error);
  158. });
  159. }
  160. _this.$__reset();
  161. _this.$__storeShard();
  162. var numAffected = 0;
  163. if (result) {
  164. if (Array.isArray(result)) {
  165. numAffected = result.length;
  166. } else if (result.result && result.result.n !== undefined) {
  167. numAffected = result.result.n;
  168. } else if (result.result && result.result.nModified !== undefined) {
  169. numAffected = result.result.nModified;
  170. } else {
  171. numAffected = result;
  172. }
  173. }
  174. // was this an update that required a version bump?
  175. if (_this.$__.version && !_this.$__.inserting) {
  176. var doIncrement = VERSION_INC === (VERSION_INC & _this.$__.version);
  177. _this.$__.version = undefined;
  178. if (numAffected <= 0) {
  179. // the update failed. pass an error back
  180. var err = new VersionError(_this);
  181. return callback(err);
  182. }
  183. // increment version if was successful
  184. if (doIncrement) {
  185. var key = _this.schema.options.versionKey;
  186. var version = _this.getValue(key) | 0;
  187. _this.setValue(key, version + 1);
  188. }
  189. }
  190. _this.emit('save', _this, numAffected);
  191. callback(null, _this, numAffected);
  192. });
  193. };
  194. /**
  195. * Saves this document.
  196. *
  197. * ####Example:
  198. *
  199. * product.sold = Date.now();
  200. * product.save(function (err, product, numAffected) {
  201. * if (err) ..
  202. * })
  203. *
  204. * The callback will receive three parameters
  205. *
  206. * 1. `err` if an error occurred
  207. * 2. `product` which is the saved `product`
  208. * 3. `numAffected` will be 1 when the document was successfully persisted to MongoDB, otherwise 0. Unless you tweak mongoose's internals, you don't need to worry about checking this parameter for errors - checking `err` is sufficient to make sure your document was properly saved.
  209. *
  210. * As an extra measure of flow control, save will return a Promise.
  211. * ####Example:
  212. * product.save().then(function(product) {
  213. * ...
  214. * });
  215. *
  216. * For legacy reasons, mongoose stores object keys in reverse order on initial
  217. * save. That is, `{ a: 1, b: 2 }` will be saved as `{ b: 2, a: 1 }` in
  218. * MongoDB. To override this behavior, set
  219. * [the `toObject.retainKeyOrder` option](http://mongoosejs.com/docs/api.html#document_Document-toObject)
  220. * to true on your schema.
  221. *
  222. * @param {Object} [options] options optional options
  223. * @param {Object} [options.safe] overrides [schema's safe option](http://mongoosejs.com//docs/guide.html#safe)
  224. * @param {Boolean} [options.validateBeforeSave] set to false to save without validating.
  225. * @param {Function} [fn] optional callback
  226. * @return {Promise} Promise
  227. * @api public
  228. * @see middleware http://mongoosejs.com/docs/middleware.html
  229. */
  230. Model.prototype.save = function(options, fn) {
  231. if (typeof options === 'function') {
  232. fn = options;
  233. options = undefined;
  234. }
  235. if (!options) {
  236. options = {};
  237. }
  238. if (fn) {
  239. fn = this.constructor.$wrapCallback(fn);
  240. }
  241. return this.$__save(options, fn);
  242. };
  243. /*!
  244. * Determines whether versioning should be skipped for the given path
  245. *
  246. * @param {Document} self
  247. * @param {String} path
  248. * @return {Boolean} true if versioning should be skipped for the given path
  249. */
  250. function shouldSkipVersioning(self, path) {
  251. var skipVersioning = self.schema.options.skipVersioning;
  252. if (!skipVersioning) return false;
  253. // Remove any array indexes from the path
  254. path = path.replace(/\.\d+\./, '.');
  255. return skipVersioning[path];
  256. }
  257. /*!
  258. * Apply the operation to the delta (update) clause as
  259. * well as track versioning for our where clause.
  260. *
  261. * @param {Document} self
  262. * @param {Object} where
  263. * @param {Object} delta
  264. * @param {Object} data
  265. * @param {Mixed} val
  266. * @param {String} [operation]
  267. */
  268. function operand(self, where, delta, data, val, op) {
  269. // delta
  270. op || (op = '$set');
  271. if (!delta[op]) delta[op] = {};
  272. delta[op][data.path] = val;
  273. // disabled versioning?
  274. if (self.schema.options.versionKey === false) return;
  275. // path excluded from versioning?
  276. if (shouldSkipVersioning(self, data.path)) return;
  277. // already marked for versioning?
  278. if (VERSION_ALL === (VERSION_ALL & self.$__.version)) return;
  279. switch (op) {
  280. case '$set':
  281. case '$unset':
  282. case '$pop':
  283. case '$pull':
  284. case '$pullAll':
  285. case '$push':
  286. case '$pushAll':
  287. case '$addToSet':
  288. break;
  289. default:
  290. // nothing to do
  291. return;
  292. }
  293. // ensure updates sent with positional notation are
  294. // editing the correct array element.
  295. // only increment the version if an array position changes.
  296. // modifying elements of an array is ok if position does not change.
  297. if (op === '$push' || op === '$pushAll' || op === '$addToSet') {
  298. self.$__.version = VERSION_INC;
  299. } else if (/^\$p/.test(op)) {
  300. // potentially changing array positions
  301. self.increment();
  302. } else if (Array.isArray(val)) {
  303. // $set an array
  304. self.increment();
  305. } else if (/\.\d+\.|\.\d+$/.test(data.path)) {
  306. // now handling $set, $unset
  307. // subpath of array
  308. self.$__.version = VERSION_WHERE;
  309. }
  310. }
  311. /*!
  312. * Compiles an update and where clause for a `val` with _atomics.
  313. *
  314. * @param {Document} self
  315. * @param {Object} where
  316. * @param {Object} delta
  317. * @param {Object} data
  318. * @param {Array} value
  319. */
  320. function handleAtomics(self, where, delta, data, value) {
  321. if (delta.$set && delta.$set[data.path]) {
  322. // $set has precedence over other atomics
  323. return;
  324. }
  325. if (typeof value.$__getAtomics === 'function') {
  326. value.$__getAtomics().forEach(function(atomic) {
  327. var op = atomic[0];
  328. var val = atomic[1];
  329. operand(self, where, delta, data, val, op);
  330. });
  331. return;
  332. }
  333. // legacy support for plugins
  334. var atomics = value._atomics,
  335. ops = Object.keys(atomics),
  336. i = ops.length,
  337. val,
  338. op;
  339. if (i === 0) {
  340. // $set
  341. if (isMongooseObject(value)) {
  342. value = value.toObject({depopulate: 1});
  343. } else if (value.valueOf) {
  344. value = value.valueOf();
  345. }
  346. return operand(self, where, delta, data, value);
  347. }
  348. function iter(mem) {
  349. return isMongooseObject(mem)
  350. ? mem.toObject({depopulate: 1})
  351. : mem;
  352. }
  353. while (i--) {
  354. op = ops[i];
  355. val = atomics[op];
  356. if (isMongooseObject(val)) {
  357. val = val.toObject({depopulate: 1});
  358. } else if (Array.isArray(val)) {
  359. val = val.map(iter);
  360. } else if (val.valueOf) {
  361. val = val.valueOf();
  362. }
  363. if (op === '$addToSet') {
  364. val = {$each: val};
  365. }
  366. operand(self, where, delta, data, val, op);
  367. }
  368. }
  369. /**
  370. * Produces a special query document of the modified properties used in updates.
  371. *
  372. * @api private
  373. * @method $__delta
  374. * @memberOf Model
  375. */
  376. Model.prototype.$__delta = function() {
  377. var dirty = this.$__dirty();
  378. if (!dirty.length && VERSION_ALL !== this.$__.version) return;
  379. var where = {},
  380. delta = {},
  381. len = dirty.length,
  382. divergent = [],
  383. d = 0;
  384. where._id = this._doc._id;
  385. for (; d < len; ++d) {
  386. var data = dirty[d];
  387. var value = data.value;
  388. var match = checkDivergentArray(this, data.path, value);
  389. if (match) {
  390. divergent.push(match);
  391. continue;
  392. }
  393. var pop = this.populated(data.path, true);
  394. if (!pop && this.$__.selected) {
  395. // If any array was selected using an $elemMatch projection, we alter the path and where clause
  396. // NOTE: MongoDB only supports projected $elemMatch on top level array.
  397. var pathSplit = data.path.split('.');
  398. var top = pathSplit[0];
  399. if (this.$__.selected[top] && this.$__.selected[top].$elemMatch) {
  400. // If the selected array entry was modified
  401. if (pathSplit.length > 1 && pathSplit[1] == 0 && typeof where[top] === 'undefined') {
  402. where[top] = this.$__.selected[top];
  403. pathSplit[1] = '$';
  404. data.path = pathSplit.join('.');
  405. }
  406. // if the selected array was modified in any other way throw an error
  407. else {
  408. divergent.push(data.path);
  409. continue;
  410. }
  411. }
  412. }
  413. if (divergent.length) continue;
  414. if (undefined === value) {
  415. operand(this, where, delta, data, 1, '$unset');
  416. } else if (value === null) {
  417. operand(this, where, delta, data, null);
  418. } else if (value._path && value._atomics) {
  419. // arrays and other custom types (support plugins etc)
  420. handleAtomics(this, where, delta, data, value);
  421. } else if (value._path && Buffer.isBuffer(value)) {
  422. // MongooseBuffer
  423. value = value.toObject();
  424. operand(this, where, delta, data, value);
  425. } else {
  426. value = utils.clone(value, {depopulate: 1});
  427. operand(this, where, delta, data, value);
  428. }
  429. }
  430. if (divergent.length) {
  431. return new DivergentArrayError(divergent);
  432. }
  433. if (this.$__.version) {
  434. this.$__version(where, delta);
  435. }
  436. return [where, delta];
  437. };
  438. /*!
  439. * Determine if array was populated with some form of filter and is now
  440. * being updated in a manner which could overwrite data unintentionally.
  441. *
  442. * @see https://github.com/Automattic/mongoose/issues/1334
  443. * @param {Document} doc
  444. * @param {String} path
  445. * @return {String|undefined}
  446. */
  447. function checkDivergentArray(doc, path, array) {
  448. // see if we populated this path
  449. var pop = doc.populated(path, true);
  450. if (!pop && doc.$__.selected) {
  451. // If any array was selected using an $elemMatch projection, we deny the update.
  452. // NOTE: MongoDB only supports projected $elemMatch on top level array.
  453. var top = path.split('.')[0];
  454. if (doc.$__.selected[top + '.$']) {
  455. return top;
  456. }
  457. }
  458. if (!(pop && array && array.isMongooseArray)) return;
  459. // If the array was populated using options that prevented all
  460. // documents from being returned (match, skip, limit) or they
  461. // deselected the _id field, $pop and $set of the array are
  462. // not safe operations. If _id was deselected, we do not know
  463. // how to remove elements. $pop will pop off the _id from the end
  464. // of the array in the db which is not guaranteed to be the
  465. // same as the last element we have here. $set of the entire array
  466. // would be similarily destructive as we never received all
  467. // elements of the array and potentially would overwrite data.
  468. var check = pop.options.match ||
  469. pop.options.options && hasOwnProperty(pop.options.options, 'limit') || // 0 is not permitted
  470. pop.options.options && pop.options.options.skip || // 0 is permitted
  471. pop.options.select && // deselected _id?
  472. (pop.options.select._id === 0 ||
  473. /\s?-_id\s?/.test(pop.options.select));
  474. if (check) {
  475. var atomics = array._atomics;
  476. if (Object.keys(atomics).length === 0 || atomics.$set || atomics.$pop) {
  477. return path;
  478. }
  479. }
  480. }
  481. /**
  482. * Appends versioning to the where and update clauses.
  483. *
  484. * @api private
  485. * @method $__version
  486. * @memberOf Model
  487. */
  488. Model.prototype.$__version = function(where, delta) {
  489. var key = this.schema.options.versionKey;
  490. if (where === true) {
  491. // this is an insert
  492. if (key) this.setValue(key, delta[key] = 0);
  493. return;
  494. }
  495. // updates
  496. // only apply versioning if our versionKey was selected. else
  497. // there is no way to select the correct version. we could fail
  498. // fast here and force them to include the versionKey but
  499. // thats a bit intrusive. can we do this automatically?
  500. if (!this.isSelected(key)) {
  501. return;
  502. }
  503. // $push $addToSet don't need the where clause set
  504. if (VERSION_WHERE === (VERSION_WHERE & this.$__.version)) {
  505. where[key] = this.getValue(key);
  506. }
  507. if (VERSION_INC === (VERSION_INC & this.$__.version)) {
  508. if (!delta.$set || typeof delta.$set[key] === 'undefined') {
  509. delta.$inc || (delta.$inc = {});
  510. delta.$inc[key] = 1;
  511. }
  512. }
  513. };
  514. /**
  515. * Signal that we desire an increment of this documents version.
  516. *
  517. * ####Example:
  518. *
  519. * Model.findById(id, function (err, doc) {
  520. * doc.increment();
  521. * doc.save(function (err) { .. })
  522. * })
  523. *
  524. * @see versionKeys http://mongoosejs.com/docs/guide.html#versionKey
  525. * @api public
  526. */
  527. Model.prototype.increment = function increment() {
  528. this.$__.version = VERSION_ALL;
  529. return this;
  530. };
  531. /**
  532. * Returns a query object which applies shardkeys if they exist.
  533. *
  534. * @api private
  535. * @method $__where
  536. * @memberOf Model
  537. */
  538. Model.prototype.$__where = function _where(where) {
  539. where || (where = {});
  540. var paths,
  541. len;
  542. if (!where._id) {
  543. where._id = this._doc._id;
  544. }
  545. if (this.$__.shardval) {
  546. paths = Object.keys(this.$__.shardval);
  547. len = paths.length;
  548. for (var i = 0; i < len; ++i) {
  549. where[paths[i]] = this.$__.shardval[paths[i]];
  550. }
  551. }
  552. if (this._doc._id == null) {
  553. return new Error('No _id found on document!');
  554. }
  555. return where;
  556. };
  557. /**
  558. * Removes this document from the db.
  559. *
  560. * ####Example:
  561. * product.remove(function (err, product) {
  562. * if (err) return handleError(err);
  563. * Product.findById(product._id, function (err, product) {
  564. * console.log(product) // null
  565. * })
  566. * })
  567. *
  568. *
  569. * As an extra measure of flow control, remove will return a Promise (bound to `fn` if passed) so it could be chained, or hooked to recive errors
  570. *
  571. * ####Example:
  572. * product.remove().then(function (product) {
  573. * ...
  574. * }).onRejected(function (err) {
  575. * assert.ok(err)
  576. * })
  577. *
  578. * @param {function(err,product)} [fn] optional callback
  579. * @return {Promise} Promise
  580. * @api public
  581. */
  582. Model.prototype.remove = function remove(options, fn) {
  583. if (typeof options === 'function') {
  584. fn = options;
  585. options = undefined;
  586. }
  587. if (!options) {
  588. options = {};
  589. }
  590. if (this.$__.removing) {
  591. if (fn) {
  592. this.$__.removing.then(
  593. function(res) { fn(null, res); },
  594. function(err) { fn(err); });
  595. }
  596. return this;
  597. }
  598. var _this = this;
  599. var Promise = PromiseProvider.get();
  600. if (fn) {
  601. fn = this.constructor.$wrapCallback(fn);
  602. }
  603. this.$__.removing = new Promise.ES6(function(resolve, reject) {
  604. var where = _this.$__where();
  605. if (where instanceof Error) {
  606. reject(where);
  607. fn && fn(where);
  608. return;
  609. }
  610. if (!options.safe && _this.schema.options.safe) {
  611. options.safe = _this.schema.options.safe;
  612. }
  613. _this.collection.remove(where, options, function(err) {
  614. if (!err) {
  615. _this.emit('remove', _this);
  616. resolve(_this);
  617. fn && fn(null, _this);
  618. return;
  619. }
  620. reject(err);
  621. fn && fn(err);
  622. });
  623. });
  624. return this.$__.removing;
  625. };
  626. /**
  627. * Returns another Model instance.
  628. *
  629. * ####Example:
  630. *
  631. * var doc = new Tank;
  632. * doc.model('User').findById(id, callback);
  633. *
  634. * @param {String} name model name
  635. * @api public
  636. */
  637. Model.prototype.model = function model(name) {
  638. return this.db.model(name);
  639. };
  640. /**
  641. * Adds a discriminator type.
  642. *
  643. * ####Example:
  644. *
  645. * function BaseSchema() {
  646. * Schema.apply(this, arguments);
  647. *
  648. * this.add({
  649. * name: String,
  650. * createdAt: Date
  651. * });
  652. * }
  653. * util.inherits(BaseSchema, Schema);
  654. *
  655. * var PersonSchema = new BaseSchema();
  656. * var BossSchema = new BaseSchema({ department: String });
  657. *
  658. * var Person = mongoose.model('Person', PersonSchema);
  659. * var Boss = Person.discriminator('Boss', BossSchema);
  660. *
  661. * @param {String} name discriminator model name
  662. * @param {Schema} schema discriminator model schema
  663. * @api public
  664. */
  665. Model.discriminator = function discriminator(name, schema) {
  666. var CUSTOMIZABLE_DISCRIMINATOR_OPTIONS = {
  667. toJSON: true,
  668. toObject: true,
  669. _id: true,
  670. id: true
  671. };
  672. if (!(schema && schema.instanceOfSchema)) {
  673. throw new Error('You must pass a valid discriminator Schema');
  674. }
  675. if (this.schema.discriminatorMapping && !this.schema.discriminatorMapping.isRoot) {
  676. throw new Error('Discriminator "' + name +
  677. '" can only be a discriminator of the root model');
  678. }
  679. var key = this.schema.options.discriminatorKey;
  680. if (schema.path(key)) {
  681. throw new Error('Discriminator "' + name +
  682. '" cannot have field with name "' + key + '"');
  683. }
  684. function merge(schema, baseSchema) {
  685. utils.merge(schema, baseSchema);
  686. var obj = {};
  687. obj[key] = {
  688. default: name,
  689. set: function() {
  690. throw new Error('Can\'t set discriminator key "' + key + '"');
  691. }
  692. };
  693. obj[key][schema.options.typeKey] = String;
  694. schema.add(obj);
  695. schema.discriminatorMapping = {key: key, value: name, isRoot: false};
  696. if (baseSchema.options.collection) {
  697. schema.options.collection = baseSchema.options.collection;
  698. }
  699. var toJSON = schema.options.toJSON;
  700. var toObject = schema.options.toObject;
  701. var _id = schema.options._id;
  702. var id = schema.options.id;
  703. var keys = Object.keys(schema.options);
  704. for (var i = 0; i < keys.length; ++i) {
  705. var _key = keys[i];
  706. if (!CUSTOMIZABLE_DISCRIMINATOR_OPTIONS[_key]) {
  707. if (!utils.deepEqual(schema.options[_key], baseSchema.options[_key])) {
  708. throw new Error('Can\'t customize discriminator option ' + _key +
  709. ' (can only modify ' +
  710. Object.keys(CUSTOMIZABLE_DISCRIMINATOR_OPTIONS).join(', ') +
  711. ')');
  712. }
  713. }
  714. }
  715. schema.options = utils.clone(baseSchema.options);
  716. if (toJSON) schema.options.toJSON = toJSON;
  717. if (toObject) schema.options.toObject = toObject;
  718. if (typeof _id !== 'undefined') {
  719. schema.options._id = _id;
  720. }
  721. schema.options.id = id;
  722. schema.callQueue = baseSchema.callQueue.concat(schema.callQueue.slice(schema._defaultMiddleware.length));
  723. schema._requiredpaths = undefined; // reset just in case Schema#requiredPaths() was called on either schema
  724. }
  725. // merges base schema into new discriminator schema and sets new type field.
  726. merge(schema, this.schema);
  727. if (!this.discriminators) {
  728. this.discriminators = {};
  729. }
  730. if (!this.schema.discriminatorMapping) {
  731. this.schema.discriminatorMapping = {key: key, value: null, isRoot: true};
  732. }
  733. if (this.discriminators[name]) {
  734. throw new Error('Discriminator with name "' + name + '" already exists');
  735. }
  736. if (this.db.models[name]) {
  737. throw new MongooseError.OverwriteModelError(name);
  738. }
  739. this.discriminators[name] = this.db.model(name, schema, this.collection.name);
  740. this.discriminators[name].prototype.__proto__ = this.prototype;
  741. Object.defineProperty(this.discriminators[name], 'baseModelName', {
  742. value: this.modelName,
  743. configurable: true,
  744. writable: false
  745. });
  746. // apply methods and statics
  747. applyMethods(this.discriminators[name], schema);
  748. applyStatics(this.discriminators[name], schema);
  749. return this.discriminators[name];
  750. };
  751. // Model (class) features
  752. /*!
  753. * Give the constructor the ability to emit events.
  754. */
  755. for (var i in EventEmitter.prototype) {
  756. Model[i] = EventEmitter.prototype[i];
  757. }
  758. /**
  759. * Called when the model compiles.
  760. *
  761. * @api private
  762. */
  763. Model.init = function init() {
  764. if ((this.schema.options.autoIndex) ||
  765. (this.schema.options.autoIndex === null && this.db.config.autoIndex)) {
  766. this.ensureIndexes({ __noPromise: true });
  767. }
  768. this.schema.emit('init', this);
  769. };
  770. /**
  771. * Sends `ensureIndex` commands to mongo for each index declared in the schema.
  772. *
  773. * ####Example:
  774. *
  775. * Event.ensureIndexes(function (err) {
  776. * if (err) return handleError(err);
  777. * });
  778. *
  779. * After completion, an `index` event is emitted on this `Model` passing an error if one occurred.
  780. *
  781. * ####Example:
  782. *
  783. * var eventSchema = new Schema({ thing: { type: 'string', unique: true }})
  784. * var Event = mongoose.model('Event', eventSchema);
  785. *
  786. * Event.on('index', function (err) {
  787. * if (err) console.error(err); // error occurred during index creation
  788. * })
  789. *
  790. * _NOTE: It is not recommended that you run this in production. Index creation may impact database performance depending on your load. Use with caution._
  791. *
  792. * The `ensureIndex` commands are not sent in parallel. This is to avoid the `MongoError: cannot add index with a background operation in progress` error. See [this ticket](https://github.com/Automattic/mongoose/issues/1365) for more information.
  793. *
  794. * @param {Object} [options] internal options
  795. * @param {Function} [cb] optional callback
  796. * @return {Promise}
  797. * @api public
  798. */
  799. Model.ensureIndexes = function ensureIndexes(options, callback) {
  800. if (typeof options === 'function') {
  801. callback = options;
  802. options = null;
  803. }
  804. if (options && options.__noPromise) {
  805. _ensureIndexes(this, callback);
  806. return;
  807. }
  808. if (callback) {
  809. callback = this.$wrapCallback(callback);
  810. }
  811. var _this = this;
  812. var Promise = PromiseProvider.get();
  813. return new Promise.ES6(function(resolve, reject) {
  814. _ensureIndexes(_this, function(error) {
  815. if (error) {
  816. callback && callback(error);
  817. reject(error);
  818. }
  819. callback && callback();
  820. resolve();
  821. });
  822. });
  823. };
  824. function _ensureIndexes(model, callback) {
  825. var indexes = model.schema.indexes();
  826. if (!indexes.length) {
  827. setImmediate(function() {
  828. callback && callback();
  829. });
  830. return;
  831. }
  832. // Indexes are created one-by-one to support how MongoDB < 2.4 deals
  833. // with background indexes.
  834. var done = function(err) {
  835. if (err && model.schema.options.emitIndexErrors) {
  836. model.emit('error', err);
  837. }
  838. model.emit('index', err);
  839. callback && callback(err);
  840. };
  841. var indexSingleDone = function(err, fields, options, name) {
  842. model.emit('index-single-done', err, fields, options, name);
  843. };
  844. var indexSingleStart = function(fields, options) {
  845. model.emit('index-single-start', fields, options);
  846. };
  847. var create = function() {
  848. var index = indexes.shift();
  849. if (!index) return done();
  850. var indexFields = index[0];
  851. var options = index[1];
  852. _handleSafe(options);
  853. indexSingleStart(indexFields, options);
  854. model.collection.ensureIndex(indexFields, options, tick(function(err, name) {
  855. indexSingleDone(err, indexFields, options, name);
  856. if (err) {
  857. return done(err);
  858. }
  859. create();
  860. }));
  861. };
  862. setImmediate(function() {
  863. create();
  864. });
  865. }
  866. function _handleSafe(options) {
  867. if (options.safe) {
  868. if (typeof options.safe === 'boolean') {
  869. options.w = options.safe;
  870. delete options.safe;
  871. }
  872. if (typeof options.safe === 'object') {
  873. options.w = options.safe.w;
  874. options.j = options.safe.j;
  875. options.wtimeout = options.safe.wtimeout;
  876. delete options.safe;
  877. }
  878. }
  879. }
  880. /**
  881. * Schema the model uses.
  882. *
  883. * @property schema
  884. * @receiver Model
  885. * @api public
  886. */
  887. Model.schema;
  888. /*!
  889. * Connection instance the model uses.
  890. *
  891. * @property db
  892. * @receiver Model
  893. * @api public
  894. */
  895. Model.db;
  896. /*!
  897. * Collection the model uses.
  898. *
  899. * @property collection
  900. * @receiver Model
  901. * @api public
  902. */
  903. Model.collection;
  904. /**
  905. * Base Mongoose instance the model uses.
  906. *
  907. * @property base
  908. * @receiver Model
  909. * @api public
  910. */
  911. Model.base;
  912. /**
  913. * Registered discriminators for this model.
  914. *
  915. * @property discriminators
  916. * @receiver Model
  917. * @api public
  918. */
  919. Model.discriminators;
  920. /**
  921. * Removes documents from the collection.
  922. *
  923. * ####Example:
  924. *
  925. * Comment.remove({ title: 'baby born from alien father' }, function (err) {
  926. *
  927. * });
  928. *
  929. * ####Note:
  930. *
  931. * To remove documents without waiting for a response from MongoDB, do not pass a `callback`, then call `exec` on the returned [Query](#query-js):
  932. *
  933. * var query = Comment.remove({ _id: id });
  934. * query.exec();
  935. *
  936. * ####Note:
  937. *
  938. * This method sends a remove command directly to MongoDB, no Mongoose documents are involved. Because no Mongoose documents are involved, _no middleware (hooks) are executed_.
  939. *
  940. * @param {Object} conditions
  941. * @param {Function} [callback]
  942. * @return {Query}
  943. * @api public
  944. */
  945. Model.remove = function remove(conditions, callback) {
  946. if (typeof conditions === 'function') {
  947. callback = conditions;
  948. conditions = {};
  949. }
  950. // get the mongodb collection object
  951. var mq = new this.Query(conditions, {}, this, this.collection);
  952. if (callback) {
  953. callback = this.$wrapCallback(callback);
  954. }
  955. return mq.remove(callback);
  956. };
  957. /**
  958. * Finds documents
  959. *
  960. * The `conditions` are cast to their respective SchemaTypes before the command is sent.
  961. *
  962. * ####Examples:
  963. *
  964. * // named john and at least 18
  965. * MyModel.find({ name: 'john', age: { $gte: 18 }});
  966. *
  967. * // executes immediately, passing results to callback
  968. * MyModel.find({ name: 'john', age: { $gte: 18 }}, function (err, docs) {});
  969. *
  970. * // name LIKE john and only selecting the "name" and "friends" fields, executing immediately
  971. * MyModel.find({ name: /john/i }, 'name friends', function (err, docs) { })
  972. *
  973. * // passing options
  974. * MyModel.find({ name: /john/i }, null, { skip: 10 })
  975. *
  976. * // passing options and executing immediately
  977. * MyModel.find({ name: /john/i }, null, { skip: 10 }, function (err, docs) {});
  978. *
  979. * // executing a query explicitly
  980. * var query = MyModel.find({ name: /john/i }, null, { skip: 10 })
  981. * query.exec(function (err, docs) {});
  982. *
  983. * // using the promise returned from executing a query
  984. * var query = MyModel.find({ name: /john/i }, null, { skip: 10 });
  985. * var promise = query.exec();
  986. * promise.addBack(function (err, docs) {});
  987. *
  988. * @param {Object} conditions
  989. * @param {Object} [projection] optional fields to return (http://bit.ly/1HotzBo)
  990. * @param {Object} [options] optional
  991. * @param {Function} [callback]
  992. * @return {Query}
  993. * @see field selection #query_Query-select
  994. * @see promise #promise-js
  995. * @api public
  996. */
  997. Model.find = function find(conditions, projection, options, callback) {
  998. if (typeof conditions === 'function') {
  999. callback = conditions;
  1000. conditions = {};
  1001. projection = null;
  1002. options = null;
  1003. } else if (typeof projection === 'function') {
  1004. callback = projection;
  1005. projection = null;
  1006. options = null;
  1007. } else if (typeof options === 'function') {
  1008. callback = options;
  1009. options = null;
  1010. }
  1011. var mq = new this.Query({}, {}, this, this.collection);
  1012. mq.select(projection);
  1013. mq.setOptions(options);
  1014. if (this.schema.discriminatorMapping && mq.selectedInclusively()) {
  1015. mq.select(this.schema.options.discriminatorKey);
  1016. }
  1017. if (callback) {
  1018. callback = this.$wrapCallback(callback);
  1019. }
  1020. return mq.find(conditions, callback);
  1021. };
  1022. /**
  1023. * Finds a single document by its _id field. `findById(id)` is almost*
  1024. * equivalent to `findOne({ _id: id })`.
  1025. *
  1026. * The `id` is cast based on the Schema before sending the command.
  1027. *
  1028. * Note: `findById()` triggers `findOne` hooks.
  1029. *
  1030. * * Except for how it treats `undefined`. Because the MongoDB driver
  1031. * deletes keys that have value `undefined`, `findById(undefined)` gets
  1032. * translated to `findById({ _id: null })`.
  1033. *
  1034. * ####Example:
  1035. *
  1036. * // find adventure by id and execute immediately
  1037. * Adventure.findById(id, function (err, adventure) {});
  1038. *
  1039. * // same as above
  1040. * Adventure.findById(id).exec(callback);
  1041. *
  1042. * // select only the adventures name and length
  1043. * Adventure.findById(id, 'name length', function (err, adventure) {});
  1044. *
  1045. * // same as above
  1046. * Adventure.findById(id, 'name length').exec(callback);
  1047. *
  1048. * // include all properties except for `length`
  1049. * Adventure.findById(id, '-length').exec(function (err, adventure) {});
  1050. *
  1051. * // passing options (in this case return the raw js objects, not mongoose documents by passing `lean`
  1052. * Adventure.findById(id, 'name', { lean: true }, function (err, doc) {});
  1053. *
  1054. * // same as above
  1055. * Adventure.findById(id, 'name').lean().exec(function (err, doc) {});
  1056. *
  1057. * @param {Object|String|Number} id value of `_id` to query by
  1058. * @param {Object} [projection] optional fields to return (http://bit.ly/1HotzBo)
  1059. * @param {Object} [options] optional
  1060. * @param {Function} [callback]
  1061. * @return {Query}
  1062. * @see field selection #query_Query-select
  1063. * @see lean queries #query_Query-lean
  1064. * @api public
  1065. */
  1066. Model.findById = function findById(id, projection, options, callback) {
  1067. if (typeof id === 'undefined') {
  1068. id = null;
  1069. }
  1070. if (callback) {
  1071. callback = this.$wrapCallback(callback);
  1072. }
  1073. return this.findOne({_id: id}, projection, options, callback);
  1074. };
  1075. /**
  1076. * Finds one document.
  1077. *
  1078. * The `conditions` are cast to their respective SchemaTypes before the command is sent.
  1079. *
  1080. * ####Example:
  1081. *
  1082. * // find one iphone adventures - iphone adventures??
  1083. * Adventure.findOne({ type: 'iphone' }, function (err, adventure) {});
  1084. *
  1085. * // same as above
  1086. * Adventure.findOne({ type: 'iphone' }).exec(function (err, adventure) {});
  1087. *
  1088. * // select only the adventures name
  1089. * Adventure.findOne({ type: 'iphone' }, 'name', function (err, adventure) {});
  1090. *
  1091. * // same as above
  1092. * Adventure.findOne({ type: 'iphone' }, 'name').exec(function (err, adventure) {});
  1093. *
  1094. * // specify options, in this case lean
  1095. * Adventure.findOne({ type: 'iphone' }, 'name', { lean: true }, callback);
  1096. *
  1097. * // same as above
  1098. * Adventure.findOne({ type: 'iphone' }, 'name', { lean: true }).exec(callback);
  1099. *
  1100. * // chaining findOne queries (same as above)
  1101. * Adventure.findOne({ type: 'iphone' }).select('name').lean().exec(callback);
  1102. *
  1103. * @param {Object} [conditions]
  1104. * @param {Object} [projection] optional fields to return (http://bit.ly/1HotzBo)
  1105. * @param {Object} [options] optional
  1106. * @param {Function} [callback]
  1107. * @return {Query}
  1108. * @see field selection #query_Query-select
  1109. * @see lean queries #query_Query-lean
  1110. * @api public
  1111. */
  1112. Model.findOne = function findOne(conditions, projection, options, callback) {
  1113. if (typeof options === 'function') {
  1114. callback = options;
  1115. options = null;
  1116. } else if (typeof projection === 'function') {
  1117. callback = projection;
  1118. projection = null;
  1119. options = null;
  1120. } else if (typeof conditions === 'function') {
  1121. callback = conditions;
  1122. conditions = {};
  1123. projection = null;
  1124. options = null;
  1125. }
  1126. // get the mongodb collection object
  1127. var mq = new this.Query({}, {}, this, this.collection);
  1128. mq.select(projection);
  1129. mq.setOptions(options);
  1130. if (this.schema.discriminatorMapping && mq.selectedInclusively()) {
  1131. mq.select(this.schema.options.discriminatorKey);
  1132. }
  1133. if (callback) {
  1134. callback = this.$wrapCallback(callback);
  1135. }
  1136. return mq.findOne(conditions, callback);
  1137. };
  1138. /**
  1139. * Counts number of matching documents in a database collection.
  1140. *
  1141. * ####Example:
  1142. *
  1143. * Adventure.count({ type: 'jungle' }, function (err, count) {
  1144. * if (err) ..
  1145. * console.log('there are %d jungle adventures', count);
  1146. * });
  1147. *
  1148. * @param {Object} conditions
  1149. * @param {Function} [callback]
  1150. * @return {Query}
  1151. * @api public
  1152. */
  1153. Model.count = function count(conditions, callback) {
  1154. if (typeof conditions === 'function') {
  1155. callback = conditions;
  1156. conditions = {};
  1157. }
  1158. // get the mongodb collection object
  1159. var mq = new this.Query({}, {}, this, this.collection);
  1160. if (callback) {
  1161. callback = this.$wrapCallback(callback);
  1162. }
  1163. return mq.count(conditions, callback);
  1164. };
  1165. /**
  1166. * Creates a Query for a `distinct` operation.
  1167. *
  1168. * Passing a `callback` immediately executes the query.
  1169. *
  1170. * ####Example
  1171. *
  1172. * Link.distinct('url', { clicks: {$gt: 100}}, function (err, result) {
  1173. * if (err) return handleError(err);
  1174. *
  1175. * assert(Array.isArray(result));
  1176. * console.log('unique urls with more than 100 clicks', result);
  1177. * })
  1178. *
  1179. * var query = Link.distinct('url');
  1180. * query.exec(callback);
  1181. *
  1182. * @param {String} field
  1183. * @param {Object} [conditions] optional
  1184. * @param {Function} [callback]
  1185. * @return {Query}
  1186. * @api public
  1187. */
  1188. Model.distinct = function distinct(field, conditions, callback) {
  1189. // get the mongodb collection object
  1190. var mq = new this.Query({}, {}, this, this.collection);
  1191. if (typeof conditions === 'function') {
  1192. callback = conditions;
  1193. conditions = {};
  1194. }
  1195. if (callback) {
  1196. callback = this.$wrapCallback(callback);
  1197. }
  1198. return mq.distinct(field, conditions, callback);
  1199. };
  1200. /**
  1201. * Creates a Query, applies the passed conditions, and returns the Query.
  1202. *
  1203. * For example, instead of writing:
  1204. *
  1205. * User.find({age: {$gte: 21, $lte: 65}}, callback);
  1206. *
  1207. * we can instead write:
  1208. *
  1209. * User.where('age').gte(21).lte(65).exec(callback);
  1210. *
  1211. * Since the Query class also supports `where` you can continue chaining
  1212. *
  1213. * User
  1214. * .where('age').gte(21).lte(65)
  1215. * .where('name', /^b/i)
  1216. * ... etc
  1217. *
  1218. * @param {String} path
  1219. * @param {Object} [val] optional value
  1220. * @return {Query}
  1221. * @api public
  1222. */
  1223. Model.where = function where(path, val) {
  1224. void val; // eslint
  1225. // get the mongodb collection object
  1226. var mq = new this.Query({}, {}, this, this.collection).find({});
  1227. return mq.where.apply(mq, arguments);
  1228. };
  1229. /**
  1230. * Creates a `Query` and specifies a `$where` condition.
  1231. *
  1232. * Sometimes you need to query for things in mongodb using a JavaScript expression. You can do so via `find({ $where: javascript })`, or you can use the mongoose shortcut method $where via a Query chain or from your mongoose Model.
  1233. *
  1234. * Blog.$where('this.username.indexOf("val") !== -1').exec(function (err, docs) {});
  1235. *
  1236. * @param {String|Function} argument is a javascript string or anonymous function
  1237. * @method $where
  1238. * @memberOf Model
  1239. * @return {Query}
  1240. * @see Query.$where #query_Query-%24where
  1241. * @api public
  1242. */
  1243. Model.$where = function $where() {
  1244. var mq = new this.Query({}, {}, this, this.collection).find({});
  1245. return mq.$where.apply(mq, arguments);
  1246. };
  1247. /**
  1248. * Issues a mongodb findAndModify update command.
  1249. *
  1250. * Finds a matching document, updates it according to the `update` arg, passing any `options`, and returns the found document (if any) to the callback. The query executes immediately if `callback` is passed else a Query object is returned.
  1251. *
  1252. * ####Options:
  1253. *
  1254. * - `new`: bool - if true, return the modified document rather than the original. defaults to false (changed in 4.0)
  1255. * - `upsert`: bool - creates the object if it doesn't exist. defaults to false.
  1256. * - `fields`: {Object|String} - Field selection. Equivalent to `.select(fields).findOneAndUpdate()`
  1257. * - `maxTimeMS`: puts a time limit on the query - requires mongodb >= 2.6.0
  1258. * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update
  1259. * - `runValidators`: if true, runs [update validators](/docs/validation.html#update-validators) on this command. Update validators validate the update operation against the model's schema.
  1260. * - `setDefaultsOnInsert`: if this and `upsert` are true, mongoose will apply the [defaults](http://mongoosejs.com/docs/defaults.html) specified in the model's schema if a new document is created. This option only works on MongoDB >= 2.4 because it relies on [MongoDB's `$setOnInsert` operator](https://docs.mongodb.org/v2.4/reference/operator/update/setOnInsert/).
  1261. * - `passRawResult`: if true, passes the [raw result from the MongoDB driver as the third callback parameter](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify)
  1262. *
  1263. *
  1264. * ####Examples:
  1265. *
  1266. * A.findOneAndUpdate(conditions, update, options, callback) // executes
  1267. * A.findOneAndUpdate(conditions, update, options) // returns Query
  1268. * A.findOneAndUpdate(conditions, update, callback) // executes
  1269. * A.findOneAndUpdate(conditions, update) // returns Query
  1270. * A.findOneAndUpdate() // returns Query
  1271. *
  1272. * ####Note:
  1273. *
  1274. * All top level update keys which are not `atomic` operation names are treated as set operations:
  1275. *
  1276. * ####Example:
  1277. *
  1278. * var query = { name: 'borne' };
  1279. * Model.findOneAndUpdate(query, { name: 'jason borne' }, options, callback)
  1280. *
  1281. * // is sent as
  1282. * Model.findOneAndUpdate(query, { $set: { name: 'jason borne' }}, options, callback)
  1283. *
  1284. * This helps prevent accidentally overwriting your document with `{ name: 'jason borne' }`.
  1285. *
  1286. * ####Note:
  1287. *
  1288. * Values are cast to their appropriate types when using the findAndModify helpers.
  1289. * However, the below are never executed.
  1290. *
  1291. * - defaults
  1292. * - setters
  1293. *
  1294. * `findAndModify` helpers support limited defaults and validation. You can
  1295. * enable these by setting the `setDefaultsOnInsert` and `runValidators` options,
  1296. * respectively.
  1297. *
  1298. * If you need full-fledged validation, use the traditional approach of first
  1299. * retrieving the document.
  1300. *
  1301. * Model.findById(id, function (err, doc) {
  1302. * if (err) ..
  1303. * doc.name = 'jason borne';
  1304. * doc.save(callback);
  1305. * });
  1306. *
  1307. * @param {Object} [conditions]
  1308. * @param {Object} [update]
  1309. * @param {Object} [options]
  1310. * @param {Function} [callback]
  1311. * @return {Query}
  1312. * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command
  1313. * @api public
  1314. */
  1315. Model.findOneAndUpdate = function(conditions, update, options, callback) {
  1316. if (typeof options === 'function') {
  1317. callback = options;
  1318. options = null;
  1319. } else if (arguments.length === 1) {
  1320. if (typeof conditions === 'function') {
  1321. var msg = 'Model.findOneAndUpdate(): First argument must not be a function.\n\n'
  1322. + ' ' + this.modelName + '.findOneAndUpdate(conditions, update, options, callback)\n'
  1323. + ' ' + this.modelName + '.findOneAndUpdate(conditions, update, options)\n'
  1324. + ' ' + this.modelName + '.findOneAndUpdate(conditions, update)\n'
  1325. + ' ' + this.modelName + '.findOneAndUpdate(update)\n'
  1326. + ' ' + this.modelName + '.findOneAndUpdate()\n';
  1327. throw new TypeError(msg);
  1328. }
  1329. update = conditions;
  1330. conditions = undefined;
  1331. }
  1332. if (callback) {
  1333. callback = this.$wrapCallback(callback);
  1334. }
  1335. var fields;
  1336. if (options && options.fields) {
  1337. fields = options.fields;
  1338. }
  1339. update = utils.clone(update, {depopulate: 1});
  1340. if (this.schema.options.versionKey && options && options.upsert) {
  1341. if (!update.$setOnInsert) {
  1342. update.$setOnInsert = {};
  1343. }
  1344. update.$setOnInsert[this.schema.options.versionKey] = 0;
  1345. }
  1346. var mq = new this.Query({}, {}, this, this.collection);
  1347. mq.select(fields);
  1348. return mq.findOneAndUpdate(conditions, update, options, callback);
  1349. };
  1350. /**
  1351. * Issues a mongodb findAndModify update command by a document's _id field.
  1352. * `findByIdAndUpdate(id, ...)` is equivalent to `findOneAndUpdate({ _id: id }, ...)`.
  1353. *
  1354. * Finds a matching document, updates it according to the `update` arg,
  1355. * passing any `options`, and returns the found document (if any) to the
  1356. * callback. The query executes immediately if `callback` is passed else a
  1357. * Query object is returned.
  1358. *
  1359. * This function triggers `findOneAndUpdate` middleware.
  1360. *
  1361. * ####Options:
  1362. *
  1363. * - `new`: bool - true to return the modified document rather than the original. defaults to false
  1364. * - `upsert`: bool - creates the object if it doesn't exist. defaults to false.
  1365. * - `runValidators`: if true, runs [update validators](/docs/validation.html#update-validators) on this command. Update validators validate the update operation against the model's schema.
  1366. * - `setDefaultsOnInsert`: if this and `upsert` are true, mongoose will apply the [defaults](http://mongoosejs.com/docs/defaults.html) specified in the model's schema if a new document is created. This option only works on MongoDB >= 2.4 because it relies on [MongoDB's `$setOnInsert` operator](https://docs.mongodb.org/v2.4/reference/operator/update/setOnInsert/).
  1367. * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update
  1368. * - `select`: sets the document fields to return
  1369. *
  1370. * ####Examples:
  1371. *
  1372. * A.findByIdAndUpdate(id, update, options, callback) // executes
  1373. * A.findByIdAndUpdate(id, update, options) // returns Query
  1374. * A.findByIdAndUpdate(id, update, callback) // executes
  1375. * A.findByIdAndUpdate(id, update) // returns Query
  1376. * A.findByIdAndUpdate() // returns Query
  1377. *
  1378. * ####Note:
  1379. *
  1380. * All top level update keys which are not `atomic` operation names are treated as set operations:
  1381. *
  1382. * ####Example:
  1383. *
  1384. * Model.findByIdAndUpdate(id, { name: 'jason borne' }, options, callback)
  1385. *
  1386. * // is sent as
  1387. * Model.findByIdAndUpdate(id, { $set: { name: 'jason borne' }}, options, callback)
  1388. *
  1389. * This helps prevent accidentally overwriting your document with `{ name: 'jason borne' }`.
  1390. *
  1391. * ####Note:
  1392. *
  1393. * Values are cast to their appropriate types when using the findAndModify helpers.
  1394. * However, the below are never executed.
  1395. *
  1396. * - defaults
  1397. * - setters
  1398. *
  1399. * `findAndModify` helpers support limited defaults and validation. You can
  1400. * enable these by setting the `setDefaultsOnInsert` and `runValidators` options,
  1401. * respectively.
  1402. *
  1403. * If you need full-fledged validation, use the traditional approach of first
  1404. * retrieving the document.
  1405. *
  1406. * Model.findById(id, function (err, doc) {
  1407. * if (err) ..
  1408. * doc.name = 'jason borne';
  1409. * doc.save(callback);
  1410. * });
  1411. *
  1412. * @param {Object|Number|String} id value of `_id` to query by
  1413. * @param {Object} [update]
  1414. * @param {Object} [options]
  1415. * @param {Function} [callback]
  1416. * @return {Query}
  1417. * @see Model.findOneAndUpdate #model_Model.findOneAndUpdate
  1418. * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command
  1419. * @api public
  1420. */
  1421. Model.findByIdAndUpdate = function(id, update, options, callback) {
  1422. if (callback) {
  1423. callback = this.$wrapCallback(callback);
  1424. }
  1425. if (arguments.length === 1) {
  1426. if (typeof id === 'function') {
  1427. var msg = 'Model.findByIdAndUpdate(): First argument must not be a function.\n\n'
  1428. + ' ' + this.modelName + '.findByIdAndUpdate(id, callback)\n'
  1429. + ' ' + this.modelName + '.findByIdAndUpdate(id)\n'
  1430. + ' ' + this.modelName + '.findByIdAndUpdate()\n';
  1431. throw new TypeError(msg);
  1432. }
  1433. return this.findOneAndUpdate({_id: id}, undefined);
  1434. }
  1435. // if a model is passed in instead of an id
  1436. if (id instanceof Document) {
  1437. id = id._id;
  1438. }
  1439. return this.findOneAndUpdate.call(this, {_id: id}, update, options, callback);
  1440. };
  1441. /**
  1442. * Issue a mongodb findAndModify remove command.
  1443. *
  1444. * Finds a matching document, removes it, passing the found document (if any) to the callback.
  1445. *
  1446. * Executes immediately if `callback` is passed else a Query object is returned.
  1447. *
  1448. * ####Options:
  1449. *
  1450. * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update
  1451. * - `maxTimeMS`: puts a time limit on the query - requires mongodb >= 2.6.0
  1452. * - `select`: sets the document fields to return
  1453. *
  1454. * ####Examples:
  1455. *
  1456. * A.findOneAndRemove(conditions, options, callback) // executes
  1457. * A.findOneAndRemove(conditions, options) // return Query
  1458. * A.findOneAndRemove(conditions, callback) // executes
  1459. * A.findOneAndRemove(conditions) // returns Query
  1460. * A.findOneAndRemove() // returns Query
  1461. *
  1462. * Values are cast to their appropriate types when using the findAndModify helpers.
  1463. * However, the below are never executed.
  1464. *
  1465. * - defaults
  1466. * - setters
  1467. *
  1468. * `findAndModify` helpers support limited defaults and validation. You can
  1469. * enable these by setting the `setDefaultsOnInsert` and `runValidators` options,
  1470. * respectively.
  1471. *
  1472. * If you need full-fledged validation, use the traditional approach of first
  1473. * retrieving the document.
  1474. *
  1475. * Model.findById(id, function (err, doc) {
  1476. * if (err) ..
  1477. * doc.name = 'jason borne';
  1478. * doc.save(callback);
  1479. * });
  1480. *
  1481. * @param {Object} conditions
  1482. * @param {Object} [options]
  1483. * @param {Function} [callback]
  1484. * @return {Query}
  1485. * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command
  1486. * @api public
  1487. */
  1488. Model.findOneAndRemove = function(conditions, options, callback) {
  1489. if (arguments.length === 1 && typeof conditions === 'function') {
  1490. var msg = 'Model.findOneAndRemove(): First argument must not be a function.\n\n'
  1491. + ' ' + this.modelName + '.findOneAndRemove(conditions, callback)\n'
  1492. + ' ' + this.modelName + '.findOneAndRemove(conditions)\n'
  1493. + ' ' + this.modelName + '.findOneAndRemove()\n';
  1494. throw new TypeError(msg);
  1495. }
  1496. if (typeof options === 'function') {
  1497. callback = options;
  1498. options = undefined;
  1499. }
  1500. if (callback) {
  1501. callback = this.$wrapCallback(callback);
  1502. }
  1503. var fields;
  1504. if (options) {
  1505. fields = options.select;
  1506. options.select = undefined;
  1507. }
  1508. var mq = new this.Query({}, {}, this, this.collection);
  1509. mq.select(fields);
  1510. return mq.findOneAndRemove(conditions, options, callback);
  1511. };
  1512. /**
  1513. * Issue a mongodb findAndModify remove command by a document's _id field. `findByIdAndRemove(id, ...)` is equivalent to `findOneAndRemove({ _id: id }, ...)`.
  1514. *
  1515. * Finds a matching document, removes it, passing the found document (if any) to the callback.
  1516. *
  1517. * Executes immediately if `callback` is passed, else a `Query` object is returned.
  1518. *
  1519. * ####Options:
  1520. *
  1521. * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update
  1522. * - `select`: sets the document fields to return
  1523. *
  1524. * ####Examples:
  1525. *
  1526. * A.findByIdAndRemove(id, options, callback) // executes
  1527. * A.findByIdAndRemove(id, options) // return Query
  1528. * A.findByIdAndRemove(id, callback) // executes
  1529. * A.findByIdAndRemove(id) // returns Query
  1530. * A.findByIdAndRemove() // returns Query
  1531. *
  1532. * @param {Object|Number|String} id value of `_id` to query by
  1533. * @param {Object} [options]
  1534. * @param {Function} [callback]
  1535. * @return {Query}
  1536. * @see Model.findOneAndRemove #model_Model.findOneAndRemove
  1537. * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command
  1538. */
  1539. Model.findByIdAndRemove = function(id, options, callback) {
  1540. if (arguments.length === 1 && typeof id === 'function') {
  1541. var msg = 'Model.findByIdAndRemove(): First argument must not be a function.\n\n'
  1542. + ' ' + this.modelName + '.findByIdAndRemove(id, callback)\n'
  1543. + ' ' + this.modelName + '.findByIdAndRemove(id)\n'
  1544. + ' ' + this.modelName + '.findByIdAndRemove()\n';
  1545. throw new TypeError(msg);
  1546. }
  1547. if (callback) {
  1548. callback = this.$wrapCallback(callback);
  1549. }
  1550. return this.findOneAndRemove({_id: id}, options, callback);
  1551. };
  1552. /**
  1553. * Shortcut for saving one or more documents to the database.
  1554. * `MyModel.create(docs)` does `new MyModel(doc).save()` for every doc in
  1555. * docs.
  1556. *
  1557. * Hooks Triggered:
  1558. * - `save()`
  1559. *
  1560. * ####Example:
  1561. *
  1562. * // pass individual docs
  1563. * Candy.create({ type: 'jelly bean' }, { type: 'snickers' }, function (err, jellybean, snickers) {
  1564. * if (err) // ...
  1565. * });
  1566. *
  1567. * // pass an array
  1568. * var array = [{ type: 'jelly bean' }, { type: 'snickers' }];
  1569. * Candy.create(array, function (err, candies) {
  1570. * if (err) // ...
  1571. *
  1572. * var jellybean = candies[0];
  1573. * var snickers = candies[1];
  1574. * // ...
  1575. * });
  1576. *
  1577. * // callback is optional; use the returned promise if you like:
  1578. * var promise = Candy.create({ type: 'jawbreaker' });
  1579. * promise.then(function (jawbreaker) {
  1580. * // ...
  1581. * })
  1582. *
  1583. * @param {Array|Object|*} doc(s)
  1584. * @param {Function} [callback] callback
  1585. * @return {Promise}
  1586. * @api public
  1587. */
  1588. Model.create = function create(doc, callback) {
  1589. var args;
  1590. var cb;
  1591. if (Array.isArray(doc)) {
  1592. args = doc;
  1593. cb = callback;
  1594. } else {
  1595. var last = arguments[arguments.length - 1];
  1596. if (typeof last === 'function') {
  1597. cb = last;
  1598. args = utils.args(arguments, 0, arguments.length - 1);
  1599. } else {
  1600. args = utils.args(arguments);
  1601. }
  1602. }
  1603. var Promise = PromiseProvider.get();
  1604. var _this = this;
  1605. if (cb) {
  1606. cb = this.$wrapCallback(cb);
  1607. }
  1608. var promise = new Promise.ES6(function(resolve, reject) {
  1609. if (args.length === 0) {
  1610. setImmediate(function() {
  1611. cb && cb(null);
  1612. resolve(null);
  1613. });
  1614. return;
  1615. }
  1616. var toExecute = [];
  1617. args.forEach(function(doc) {
  1618. toExecute.push(function(callback) {
  1619. var toSave = new _this(doc);
  1620. var callbackWrapper = function(error, doc) {
  1621. if (error) {
  1622. return callback(error);
  1623. }
  1624. callback(null, doc);
  1625. };
  1626. // Hack to avoid getting a promise because of
  1627. // $__registerHooksFromSchema
  1628. if (toSave.$__original_save) {
  1629. toSave.$__original_save({ __noPromise: true }, callbackWrapper);
  1630. } else {
  1631. toSave.save({ __noPromise: true }, callbackWrapper);
  1632. }
  1633. });
  1634. });
  1635. async.parallel(toExecute, function(error, savedDocs) {
  1636. if (error) {
  1637. cb && cb(error);
  1638. reject(error);
  1639. return;
  1640. }
  1641. if (doc instanceof Array) {
  1642. resolve(savedDocs);
  1643. cb && cb.call(_this, null, savedDocs);
  1644. } else {
  1645. resolve.apply(promise, savedDocs);
  1646. if (cb) {
  1647. savedDocs.unshift(null);
  1648. cb.apply(_this, savedDocs);
  1649. }
  1650. }
  1651. });
  1652. });
  1653. return promise;
  1654. };
  1655. /**
  1656. * Shortcut for validating an array of documents and inserting them into
  1657. * MongoDB if they're all valid. This function is faster than `.create()`
  1658. * because it only sends one operation to the server, rather than one for each
  1659. * document.
  1660. *
  1661. * This function does **not** trigger save middleware.
  1662. *
  1663. * ####Example:
  1664. *
  1665. * var arr = [{ name: 'Star Wars' }, { name: 'The Empire Strikes Back' }];
  1666. * Movies.insertMany(arr, function(error, docs) {});
  1667. *
  1668. * @param {Array|Object|*} doc(s)
  1669. * @param {Function} [callback] callback
  1670. * @return {Promise}
  1671. * @api public
  1672. */
  1673. Model.insertMany = function(arr, callback) {
  1674. var _this = this;
  1675. if (callback) {
  1676. callback = this.$wrapCallback(callback);
  1677. }
  1678. var toExecute = [];
  1679. arr.forEach(function(doc) {
  1680. toExecute.push(function(callback) {
  1681. doc = new _this(doc);
  1682. doc.validate({ __noPromise: true }, function(error) {
  1683. if (error) {
  1684. return callback(error);
  1685. }
  1686. callback(null, doc);
  1687. });
  1688. });
  1689. });
  1690. async.parallel(toExecute, function(error, docs) {
  1691. if (error) {
  1692. callback && callback(error);
  1693. return;
  1694. }
  1695. var docObjects = docs.map(function(doc) {
  1696. if (doc.initializeTimestamps) {
  1697. return doc.initializeTimestamps().toObject({ virtuals: false });
  1698. }
  1699. return doc.toObject({ virtuals: false });
  1700. });
  1701. _this.collection.insertMany(docObjects, function(error) {
  1702. if (error) {
  1703. callback && callback(error);
  1704. return;
  1705. }
  1706. for (var i = 0; i < docs.length; ++i) {
  1707. docs[i].isNew = false;
  1708. docs[i].emit('isNew', false);
  1709. }
  1710. callback && callback(null, docs);
  1711. });
  1712. });
  1713. };
  1714. /**
  1715. * Shortcut for creating a new Document from existing raw data, pre-saved in the DB.
  1716. * The document returned has no paths marked as modified initially.
  1717. *
  1718. * ####Example:
  1719. *
  1720. * // hydrate previous data into a Mongoose document
  1721. * var mongooseCandy = Candy.hydrate({ _id: '54108337212ffb6d459f854c', type: 'jelly bean' });
  1722. *
  1723. * @param {Object} obj
  1724. * @return {Document}
  1725. * @api public
  1726. */
  1727. Model.hydrate = function(obj) {
  1728. var model = require('./queryhelpers').createModel(this, obj);
  1729. model.init(obj);
  1730. return model;
  1731. };
  1732. /**
  1733. * Updates documents in the database without returning them.
  1734. *
  1735. * ####Examples:
  1736. *
  1737. * MyModel.update({ age: { $gt: 18 } }, { oldEnough: true }, fn);
  1738. * MyModel.update({ name: 'Tobi' }, { ferret: true }, { multi: true }, function (err, raw) {
  1739. * if (err) return handleError(err);
  1740. * console.log('The raw response from Mongo was ', raw);
  1741. * });
  1742. *
  1743. * ####Valid options:
  1744. *
  1745. * - `safe` (boolean) safe mode (defaults to value set in schema (true))
  1746. * - `upsert` (boolean) whether to create the doc if it doesn't match (false)
  1747. * - `multi` (boolean) whether multiple documents should be updated (false)
  1748. * - `runValidators`: if true, runs [update validators](/docs/validation.html#update-validators) on this command. Update validators validate the update operation against the model's schema.
  1749. * - `setDefaultsOnInsert`: if this and `upsert` are true, mongoose will apply the [defaults](http://mongoosejs.com/docs/defaults.html) specified in the model's schema if a new document is created. This option only works on MongoDB >= 2.4 because it relies on [MongoDB's `$setOnInsert` operator](https://docs.mongodb.org/v2.4/reference/operator/update/setOnInsert/).
  1750. * - `strict` (boolean) overrides the `strict` option for this update
  1751. * - `overwrite` (boolean) disables update-only mode, allowing you to overwrite the doc (false)
  1752. *
  1753. * All `update` values are cast to their appropriate SchemaTypes before being sent.
  1754. *
  1755. * The `callback` function receives `(err, rawResponse)`.
  1756. *
  1757. * - `err` is the error if any occurred
  1758. * - `rawResponse` is the full response from Mongo
  1759. *
  1760. * ####Note:
  1761. *
  1762. * All top level keys which are not `atomic` operation names are treated as set operations:
  1763. *
  1764. * ####Example:
  1765. *
  1766. * var query = { name: 'borne' };
  1767. * Model.update(query, { name: 'jason borne' }, options, callback)
  1768. *
  1769. * // is sent as
  1770. * Model.update(query, { $set: { name: 'jason borne' }}, options, callback)
  1771. * // if overwrite option is false. If overwrite is true, sent without the $set wrapper.
  1772. *
  1773. * This helps prevent accidentally overwriting all documents in your collection with `{ name: 'jason borne' }`.
  1774. *
  1775. * ####Note:
  1776. *
  1777. * Be careful to not use an existing model instance for the update clause (this won't work and can cause weird behavior like infinite loops). Also, ensure that the update clause does not have an _id property, which causes Mongo to return a "Mod on _id not allowed" error.
  1778. *
  1779. * ####Note:
  1780. *
  1781. * To update documents without waiting for a response from MongoDB, do not pass a `callback`, then call `exec` on the returned [Query](#query-js):
  1782. *
  1783. * Comment.update({ _id: id }, { $set: { text: 'changed' }}).exec();
  1784. *
  1785. * ####Note:
  1786. *
  1787. * Although values are casted to their appropriate types when using update, the following are *not* applied:
  1788. *
  1789. * - defaults
  1790. * - setters
  1791. * - validators
  1792. * - middleware
  1793. *
  1794. * If you need those features, use the traditional approach of first retrieving the document.
  1795. *
  1796. * Model.findOne({ name: 'borne' }, function (err, doc) {
  1797. * if (err) ..
  1798. * doc.name = 'jason borne';
  1799. * doc.save(callback);
  1800. * })
  1801. *
  1802. * @see strict http://mongoosejs.com/docs/guide.html#strict
  1803. * @see response http://docs.mongodb.org/v2.6/reference/command/update/#output
  1804. * @param {Object} conditions
  1805. * @param {Object} doc
  1806. * @param {Object} [options]
  1807. * @param {Function} [callback]
  1808. * @return {Query}
  1809. * @api public
  1810. */
  1811. Model.update = function update(conditions, doc, options, callback) {
  1812. var mq = new this.Query({}, {}, this, this.collection);
  1813. if (callback) {
  1814. callback = this.$wrapCallback(callback);
  1815. }
  1816. // gh-2406
  1817. // make local deep copy of conditions
  1818. if (conditions instanceof Document) {
  1819. conditions = conditions.toObject();
  1820. } else {
  1821. conditions = utils.clone(conditions, {retainKeyOrder: true});
  1822. }
  1823. options = typeof options === 'function' ? options : utils.clone(options);
  1824. return mq.update(conditions, doc, options, callback);
  1825. };
  1826. /**
  1827. * Executes a mapReduce command.
  1828. *
  1829. * `o` is an object specifying all mapReduce options as well as the map and reduce functions. All options are delegated to the driver implementation. See [node-mongodb-native mapReduce() documentation](http://mongodb.github.io/node-mongodb-native/api-generated/collection.html#mapreduce) for more detail about options.
  1830. *
  1831. * ####Example:
  1832. *
  1833. * var o = {};
  1834. * o.map = function () { emit(this.name, 1) }
  1835. * o.reduce = function (k, vals) { return vals.length }
  1836. * User.mapReduce(o, function (err, results) {
  1837. * console.log(results)
  1838. * })
  1839. *
  1840. * ####Other options:
  1841. *
  1842. * - `query` {Object} query filter object.
  1843. * - `sort` {Object} sort input objects using this key
  1844. * - `limit` {Number} max number of documents
  1845. * - `keeptemp` {Boolean, default:false} keep temporary data
  1846. * - `finalize` {Function} finalize function
  1847. * - `scope` {Object} scope variables exposed to map/reduce/finalize during execution
  1848. * - `jsMode` {Boolean, default:false} it is possible to make the execution stay in JS. Provided in MongoDB > 2.0.X
  1849. * - `verbose` {Boolean, default:false} provide statistics on job execution time.
  1850. * - `readPreference` {String}
  1851. * - `out*` {Object, default: {inline:1}} sets the output target for the map reduce job.
  1852. *
  1853. * ####* out options:
  1854. *
  1855. * - `{inline:1}` the results are returned in an array
  1856. * - `{replace: 'collectionName'}` add the results to collectionName: the results replace the collection
  1857. * - `{reduce: 'collectionName'}` add the results to collectionName: if dups are detected, uses the reducer / finalize functions
  1858. * - `{merge: 'collectionName'}` add the results to collectionName: if dups exist the new docs overwrite the old
  1859. *
  1860. * If `options.out` is set to `replace`, `merge`, or `reduce`, a Model instance is returned that can be used for further querying. Queries run against this model are all executed with the `lean` option; meaning only the js object is returned and no Mongoose magic is applied (getters, setters, etc).
  1861. *
  1862. * ####Example:
  1863. *
  1864. * var o = {};
  1865. * o.map = function () { emit(this.name, 1) }
  1866. * o.reduce = function (k, vals) { return vals.length }
  1867. * o.out = { replace: 'createdCollectionNameForResults' }
  1868. * o.verbose = true;
  1869. *
  1870. * User.mapReduce(o, function (err, model, stats) {
  1871. * console.log('map reduce took %d ms', stats.processtime)
  1872. * model.find().where('value').gt(10).exec(function (err, docs) {
  1873. * console.log(docs);
  1874. * });
  1875. * })
  1876. *
  1877. * // a promise is returned so you may instead write
  1878. * var promise = User.mapReduce(o);
  1879. * promise.then(function (model, stats) {
  1880. * console.log('map reduce took %d ms', stats.processtime)
  1881. * return model.find().where('value').gt(10).exec();
  1882. * }).then(function (docs) {
  1883. * console.log(docs);
  1884. * }).then(null, handleError).end()
  1885. *
  1886. * @param {Object} o an object specifying map-reduce options
  1887. * @param {Function} [callback] optional callback
  1888. * @see http://www.mongodb.org/display/DOCS/MapReduce
  1889. * @return {Promise}
  1890. * @api public
  1891. */
  1892. Model.mapReduce = function mapReduce(o, callback) {
  1893. var _this = this;
  1894. if (callback) {
  1895. callback = this.$wrapCallback(callback);
  1896. }
  1897. var Promise = PromiseProvider.get();
  1898. return new Promise.ES6(function(resolve, reject) {
  1899. if (!Model.mapReduce.schema) {
  1900. var opts = {noId: true, noVirtualId: true, strict: false};
  1901. Model.mapReduce.schema = new Schema({}, opts);
  1902. }
  1903. if (!o.out) o.out = {inline: 1};
  1904. if (o.verbose !== false) o.verbose = true;
  1905. o.map = String(o.map);
  1906. o.reduce = String(o.reduce);
  1907. if (o.query) {
  1908. var q = new _this.Query(o.query);
  1909. q.cast(_this);
  1910. o.query = q._conditions;
  1911. q = undefined;
  1912. }
  1913. _this.collection.mapReduce(null, null, o, function(err, ret, stats) {
  1914. if (err) {
  1915. callback && callback(err);
  1916. reject(err);
  1917. return;
  1918. }
  1919. if (ret.findOne && ret.mapReduce) {
  1920. // returned a collection, convert to Model
  1921. var model = Model.compile(
  1922. '_mapreduce_' + ret.collectionName
  1923. , Model.mapReduce.schema
  1924. , ret.collectionName
  1925. , _this.db
  1926. , _this.base);
  1927. model._mapreduce = true;
  1928. callback && callback(null, model, stats);
  1929. return resolve(model, stats);
  1930. }
  1931. callback && callback(null, ret, stats);
  1932. resolve(ret, stats);
  1933. });
  1934. });
  1935. };
  1936. /**
  1937. * geoNear support for Mongoose
  1938. *
  1939. * ####Options:
  1940. * - `lean` {Boolean} return the raw object
  1941. * - All options supported by the driver are also supported
  1942. *
  1943. * ####Example:
  1944. *
  1945. * // Legacy point
  1946. * Model.geoNear([1,3], { maxDistance : 5, spherical : true }, function(err, results, stats) {
  1947. * console.log(results);
  1948. * });
  1949. *
  1950. * // geoJson
  1951. * var point = { type : "Point", coordinates : [9,9] };
  1952. * Model.geoNear(point, { maxDistance : 5, spherical : true }, function(err, results, stats) {
  1953. * console.log(results);
  1954. * });
  1955. *
  1956. * @param {Object|Array} GeoJSON point or legacy coordinate pair [x,y] to search near
  1957. * @param {Object} options for the qurery
  1958. * @param {Function} [callback] optional callback for the query
  1959. * @return {Promise}
  1960. * @see http://docs.mongodb.org/manual/core/2dsphere/
  1961. * @see http://mongodb.github.io/node-mongodb-native/api-generated/collection.html?highlight=geonear#geoNear
  1962. * @api public
  1963. */
  1964. Model.geoNear = function(near, options, callback) {
  1965. if (typeof options === 'function') {
  1966. callback = options;
  1967. options = {};
  1968. }
  1969. if (callback) {
  1970. callback = this.$wrapCallback(callback);
  1971. }
  1972. var _this = this;
  1973. var Promise = PromiseProvider.get();
  1974. if (!near) {
  1975. return new Promise.ES6(function(resolve, reject) {
  1976. var error = new Error('Must pass a near option to geoNear');
  1977. reject(error);
  1978. callback && callback(error);
  1979. });
  1980. }
  1981. var x, y;
  1982. return new Promise.ES6(function(resolve, reject) {
  1983. var handler = function(err, res) {
  1984. if (err) {
  1985. reject(err);
  1986. callback && callback(err);
  1987. return;
  1988. }
  1989. if (options.lean) {
  1990. resolve(res.results, res.stats);
  1991. callback && callback(null, res.results, res.stats);
  1992. return;
  1993. }
  1994. var count = res.results.length;
  1995. // if there are no results, fulfill the promise now
  1996. if (count === 0) {
  1997. resolve(res.results, res.stats);
  1998. callback && callback(null, res.results, res.stats);
  1999. return;
  2000. }
  2001. var errSeen = false;
  2002. function init(err) {
  2003. if (err && !errSeen) {
  2004. errSeen = true;
  2005. reject(err);
  2006. callback && callback(err);
  2007. return;
  2008. }
  2009. if (--count <= 0) {
  2010. resolve(res.results, res.stats);
  2011. callback && callback(null, res.results, res.stats);
  2012. }
  2013. }
  2014. for (var i = 0; i < res.results.length; i++) {
  2015. var temp = res.results[i].obj;
  2016. res.results[i].obj = new _this();
  2017. res.results[i].obj.init(temp, init);
  2018. }
  2019. };
  2020. if (Array.isArray(near)) {
  2021. if (near.length !== 2) {
  2022. var error = new Error('If using legacy coordinates, must be an array ' +
  2023. 'of size 2 for geoNear');
  2024. reject(error);
  2025. callback && callback(error);
  2026. return;
  2027. }
  2028. x = near[0];
  2029. y = near[1];
  2030. _this.collection.geoNear(x, y, options, handler);
  2031. } else {
  2032. if (near.type !== 'Point' || !Array.isArray(near.coordinates)) {
  2033. error = new Error('Must pass either a legacy coordinate array or ' +
  2034. 'GeoJSON Point to geoNear');
  2035. reject(error);
  2036. callback && callback(error);
  2037. return;
  2038. }
  2039. _this.collection.geoNear(near, options, handler);
  2040. }
  2041. });
  2042. };
  2043. /**
  2044. * Performs [aggregations](http://docs.mongodb.org/manual/applications/aggregation/) on the models collection.
  2045. *
  2046. * If a `callback` is passed, the `aggregate` is executed and a `Promise` is returned. If a callback is not passed, the `aggregate` itself is returned.
  2047. *
  2048. * ####Example:
  2049. *
  2050. * // Find the max balance of all accounts
  2051. * Users.aggregate(
  2052. * { $group: { _id: null, maxBalance: { $max: '$balance' }}}
  2053. * , { $project: { _id: 0, maxBalance: 1 }}
  2054. * , function (err, res) {
  2055. * if (err) return handleError(err);
  2056. * console.log(res); // [ { maxBalance: 98000 } ]
  2057. * });
  2058. *
  2059. * // Or use the aggregation pipeline builder.
  2060. * Users.aggregate()
  2061. * .group({ _id: null, maxBalance: { $max: '$balance' } })
  2062. * .select('-id maxBalance')
  2063. * .exec(function (err, res) {
  2064. * if (err) return handleError(err);
  2065. * console.log(res); // [ { maxBalance: 98 } ]
  2066. * });
  2067. *
  2068. * ####NOTE:
  2069. *
  2070. * - Arguments are not cast to the model's schema because `$project` operators allow redefining the "shape" of the documents at any stage of the pipeline, which may leave documents in an incompatible format.
  2071. * - The documents returned are plain javascript objects, not mongoose documents (since any shape of document can be returned).
  2072. * - Requires MongoDB >= 2.1
  2073. *
  2074. * @see Aggregate #aggregate_Aggregate
  2075. * @see MongoDB http://docs.mongodb.org/manual/applications/aggregation/
  2076. * @param {Object|Array} [...] aggregation pipeline operator(s) or operator array
  2077. * @param {Function} [callback]
  2078. * @return {Aggregate|Promise}
  2079. * @api public
  2080. */
  2081. Model.aggregate = function aggregate() {
  2082. var args = [].slice.call(arguments),
  2083. aggregate,
  2084. callback;
  2085. if (typeof args[args.length - 1] === 'function') {
  2086. callback = args.pop();
  2087. }
  2088. if (args.length === 1 && util.isArray(args[0])) {
  2089. aggregate = new Aggregate(args[0]);
  2090. } else {
  2091. aggregate = new Aggregate(args);
  2092. }
  2093. aggregate.model(this);
  2094. if (typeof callback === 'undefined') {
  2095. return aggregate;
  2096. }
  2097. if (callback) {
  2098. callback = this.$wrapCallback(callback);
  2099. }
  2100. aggregate.exec(callback);
  2101. };
  2102. /**
  2103. * Implements `$geoSearch` functionality for Mongoose
  2104. *
  2105. * ####Example:
  2106. *
  2107. * var options = { near: [10, 10], maxDistance: 5 };
  2108. * Locations.geoSearch({ type : "house" }, options, function(err, res) {
  2109. * console.log(res);
  2110. * });
  2111. *
  2112. * ####Options:
  2113. * - `near` {Array} x,y point to search for
  2114. * - `maxDistance` {Number} the maximum distance from the point near that a result can be
  2115. * - `limit` {Number} The maximum number of results to return
  2116. * - `lean` {Boolean} return the raw object instead of the Mongoose Model
  2117. *
  2118. * @param {Object} conditions an object that specifies the match condition (required)
  2119. * @param {Object} options for the geoSearch, some (near, maxDistance) are required
  2120. * @param {Function} [callback] optional callback
  2121. * @return {Promise}
  2122. * @see http://docs.mongodb.org/manual/reference/command/geoSearch/
  2123. * @see http://docs.mongodb.org/manual/core/geohaystack/
  2124. * @api public
  2125. */
  2126. Model.geoSearch = function(conditions, options, callback) {
  2127. if (typeof options === 'function') {
  2128. callback = options;
  2129. options = {};
  2130. }
  2131. if (callback) {
  2132. callback = this.$wrapCallback(callback);
  2133. }
  2134. var _this = this;
  2135. var Promise = PromiseProvider.get();
  2136. return new Promise.ES6(function(resolve, reject) {
  2137. var error;
  2138. if (conditions === undefined || !utils.isObject(conditions)) {
  2139. error = new Error('Must pass conditions to geoSearch');
  2140. } else if (!options.near) {
  2141. error = new Error('Must specify the near option in geoSearch');
  2142. } else if (!Array.isArray(options.near)) {
  2143. error = new Error('near option must be an array [x, y]');
  2144. }
  2145. if (error) {
  2146. callback && callback(error);
  2147. reject(error);
  2148. return;
  2149. }
  2150. // send the conditions in the options object
  2151. options.search = conditions;
  2152. _this.collection.geoHaystackSearch(options.near[0], options.near[1], options, function(err, res) {
  2153. // have to deal with driver problem. Should be fixed in a soon-ish release
  2154. // (7/8/2013)
  2155. if (err) {
  2156. callback && callback(err);
  2157. reject(err);
  2158. return;
  2159. }
  2160. var count = res.results.length;
  2161. if (options.lean || count === 0) {
  2162. callback && callback(null, res.results, res.stats);
  2163. resolve(res.results, res.stats);
  2164. return;
  2165. }
  2166. var errSeen = false;
  2167. function init(err) {
  2168. if (err && !errSeen) {
  2169. callback && callback(err);
  2170. reject(err);
  2171. return;
  2172. }
  2173. if (!--count && !errSeen) {
  2174. callback && callback(null, res.results, res.stats);
  2175. resolve(res.results, res.stats);
  2176. }
  2177. }
  2178. for (var i = 0; i < res.results.length; i++) {
  2179. var temp = res.results[i];
  2180. res.results[i] = new _this();
  2181. res.results[i].init(temp, {}, init);
  2182. }
  2183. });
  2184. });
  2185. };
  2186. /**
  2187. * Populates document references.
  2188. *
  2189. * ####Available options:
  2190. *
  2191. * - path: space delimited path(s) to populate
  2192. * - select: optional fields to select
  2193. * - match: optional query conditions to match
  2194. * - model: optional name of the model to use for population
  2195. * - options: optional query options like sort, limit, etc
  2196. *
  2197. * ####Examples:
  2198. *
  2199. * // populates a single object
  2200. * User.findById(id, function (err, user) {
  2201. * var opts = [
  2202. * { path: 'company', match: { x: 1 }, select: 'name' }
  2203. * , { path: 'notes', options: { limit: 10 }, model: 'override' }
  2204. * ]
  2205. *
  2206. * User.populate(user, opts, function (err, user) {
  2207. * console.log(user);
  2208. * })
  2209. * })
  2210. *
  2211. * // populates an array of objects
  2212. * User.find(match, function (err, users) {
  2213. * var opts = [{ path: 'company', match: { x: 1 }, select: 'name' }]
  2214. *
  2215. * var promise = User.populate(users, opts);
  2216. * promise.then(console.log).end();
  2217. * })
  2218. *
  2219. * // imagine a Weapon model exists with two saved documents:
  2220. * // { _id: 389, name: 'whip' }
  2221. * // { _id: 8921, name: 'boomerang' }
  2222. *
  2223. * var user = { name: 'Indiana Jones', weapon: 389 }
  2224. * Weapon.populate(user, { path: 'weapon', model: 'Weapon' }, function (err, user) {
  2225. * console.log(user.weapon.name) // whip
  2226. * })
  2227. *
  2228. * // populate many plain objects
  2229. * var users = [{ name: 'Indiana Jones', weapon: 389 }]
  2230. * users.push({ name: 'Batman', weapon: 8921 })
  2231. * Weapon.populate(users, { path: 'weapon' }, function (err, users) {
  2232. * users.forEach(function (user) {
  2233. * console.log('%s uses a %s', users.name, user.weapon.name)
  2234. * // Indiana Jones uses a whip
  2235. * // Batman uses a boomerang
  2236. * })
  2237. * })
  2238. * // Note that we didn't need to specify the Weapon model because
  2239. * // we were already using it's populate() method.
  2240. *
  2241. * @param {Document|Array} docs Either a single document or array of documents to populate.
  2242. * @param {Object} options A hash of key/val (path, options) used for population.
  2243. * @param {Function} [callback(err,doc)] Optional callback, executed upon completion. Receives `err` and the `doc(s)`.
  2244. * @return {Promise}
  2245. * @api public
  2246. */
  2247. Model.populate = function(docs, paths, callback) {
  2248. var _this = this;
  2249. if (callback) {
  2250. callback = this.$wrapCallback(callback);
  2251. }
  2252. // normalized paths
  2253. var noPromise = paths && !!paths.__noPromise;
  2254. paths = utils.populate(paths);
  2255. // data that should persist across subPopulate calls
  2256. var cache = {};
  2257. if (noPromise) {
  2258. _populate(this, docs, paths, cache, callback);
  2259. } else {
  2260. var Promise = PromiseProvider.get();
  2261. return new Promise.ES6(function(resolve, reject) {
  2262. _populate(_this, docs, paths, cache, function(error, docs) {
  2263. if (error) {
  2264. callback && callback(error);
  2265. reject(error);
  2266. } else {
  2267. callback && callback(null, docs);
  2268. resolve(docs);
  2269. }
  2270. });
  2271. });
  2272. }
  2273. };
  2274. /*!
  2275. * Populate helper
  2276. *
  2277. * @param {Model} model the model to use
  2278. * @param {Document|Array} docs Either a single document or array of documents to populate.
  2279. * @param {Object} paths
  2280. * @param {Function} [cb(err,doc)] Optional callback, executed upon completion. Receives `err` and the `doc(s)`.
  2281. * @return {Function}
  2282. * @api private
  2283. */
  2284. function _populate(model, docs, paths, cache, callback) {
  2285. var pending = paths.length;
  2286. if (pending === 0) {
  2287. return callback(null, docs);
  2288. }
  2289. // each path has its own query options and must be executed separately
  2290. var i = pending;
  2291. var path;
  2292. while (i--) {
  2293. path = paths[i];
  2294. populate(model, docs, path, next);
  2295. }
  2296. function next(err) {
  2297. if (err) {
  2298. return callback(err);
  2299. }
  2300. if (--pending) {
  2301. return;
  2302. }
  2303. callback(null, docs);
  2304. }
  2305. }
  2306. /*!
  2307. * Populates `docs`
  2308. */
  2309. var excludeIdReg = /\s?-_id\s?/,
  2310. excludeIdRegGlobal = /\s?-_id\s?/g;
  2311. function populate(model, docs, options, callback) {
  2312. var modelsMap;
  2313. // normalize single / multiple docs passed
  2314. if (!Array.isArray(docs)) {
  2315. docs = [docs];
  2316. }
  2317. if (docs.length === 0 || docs.every(utils.isNullOrUndefined)) {
  2318. return callback();
  2319. }
  2320. modelsMap = getModelsMapForPopulate(model, docs, options);
  2321. var i, len = modelsMap.length,
  2322. mod, match, select, vals = [];
  2323. function flatten(item) {
  2324. // no need to include undefined values in our query
  2325. return undefined !== item;
  2326. }
  2327. var _remaining = len;
  2328. var hasOne = false;
  2329. for (i = 0; i < len; i++) {
  2330. mod = modelsMap[i];
  2331. select = mod.options.select;
  2332. if (mod.options.match) {
  2333. match = utils.object.shallowCopy(mod.options.match);
  2334. } else {
  2335. match = {};
  2336. }
  2337. var ids = utils.array.flatten(mod.ids, flatten);
  2338. ids = utils.array.unique(ids);
  2339. if (ids.length === 0 || ids.every(utils.isNullOrUndefined)) {
  2340. --_remaining;
  2341. continue;
  2342. }
  2343. hasOne = true;
  2344. if (mod.foreignField !== '_id' || !match['_id']) {
  2345. match[mod.foreignField] = { $in: ids };
  2346. }
  2347. var assignmentOpts = {};
  2348. assignmentOpts.sort = mod.options.options && mod.options.options.sort || undefined;
  2349. assignmentOpts.excludeId = excludeIdReg.test(select) || (select && select._id === 0);
  2350. if (assignmentOpts.excludeId) {
  2351. // override the exclusion from the query so we can use the _id
  2352. // for document matching during assignment. we'll delete the
  2353. // _id back off before returning the result.
  2354. if (typeof select === 'string') {
  2355. select = select.replace(excludeIdRegGlobal, ' ');
  2356. } else {
  2357. // preserve original select conditions by copying
  2358. select = utils.object.shallowCopy(select);
  2359. delete select._id;
  2360. }
  2361. }
  2362. if (mod.options.options && mod.options.options.limit) {
  2363. assignmentOpts.originalLimit = mod.options.options.limit;
  2364. mod.options.options.limit = mod.options.options.limit * ids.length;
  2365. }
  2366. var subPopulate = mod.options.populate;
  2367. var query = mod.Model.find(match, select, mod.options.options);
  2368. if (subPopulate) {
  2369. query.populate(subPopulate);
  2370. }
  2371. query.exec(next.bind(this, mod, assignmentOpts));
  2372. }
  2373. if (!hasOne) {
  2374. return callback();
  2375. }
  2376. function next(options, assignmentOpts, err, valsFromDb) {
  2377. if (err) return callback(err);
  2378. vals = vals.concat(valsFromDb);
  2379. _assign(null, vals, options, assignmentOpts);
  2380. if (--_remaining === 0) {
  2381. callback();
  2382. }
  2383. }
  2384. function _assign(err, vals, mod, assignmentOpts) {
  2385. if (err) return callback(err);
  2386. var options = mod.options;
  2387. var _val;
  2388. var lean = options.options && options.options.lean,
  2389. len = vals.length,
  2390. rawOrder = {}, rawDocs = {}, key, val;
  2391. // optimization:
  2392. // record the document positions as returned by
  2393. // the query result.
  2394. for (var i = 0; i < len; i++) {
  2395. val = vals[i];
  2396. if (val) {
  2397. _val = utils.getValue(mod.foreignField, val);
  2398. if (Array.isArray(_val)) {
  2399. var _valLength = _val.length;
  2400. for (var j = 0; j < _valLength; ++j) {
  2401. key = String(_val[j]);
  2402. if (rawDocs[key]) {
  2403. if (Array.isArray(rawDocs[key])) {
  2404. rawDocs[key].push(val);
  2405. rawOrder[key].push(i);
  2406. } else {
  2407. rawDocs[key] = [rawDocs[key], val];
  2408. rawOrder[key] = [rawOrder[key], i];
  2409. }
  2410. } else {
  2411. rawDocs[key] = val;
  2412. rawOrder[key] = i;
  2413. }
  2414. }
  2415. } else {
  2416. key = String(utils.getValue(mod.foreignField, val));
  2417. if (rawDocs[key]) {
  2418. if (Array.isArray(rawDocs[key])) {
  2419. rawDocs[key].push(val);
  2420. rawOrder[key].push(i);
  2421. } else {
  2422. rawDocs[key] = [rawDocs[key], val];
  2423. rawOrder[key] = [rawOrder[key], i];
  2424. }
  2425. } else {
  2426. rawDocs[key] = val;
  2427. rawOrder[key] = i;
  2428. }
  2429. }
  2430. // flag each as result of population
  2431. if (!lean) {
  2432. val.$__.wasPopulated = true;
  2433. }
  2434. }
  2435. }
  2436. assignVals({
  2437. originalModel: model,
  2438. rawIds: mod.ids,
  2439. localField: mod.localField,
  2440. foreignField: mod.foreignField,
  2441. rawDocs: rawDocs,
  2442. rawOrder: rawOrder,
  2443. docs: mod.docs,
  2444. path: options.path,
  2445. options: assignmentOpts,
  2446. justOne: mod.justOne,
  2447. isVirtual: mod.isVirtual
  2448. });
  2449. }
  2450. }
  2451. /*!
  2452. * Assigns documents returned from a population query back
  2453. * to the original document path.
  2454. */
  2455. function assignVals(o) {
  2456. // replace the original ids in our intermediate _ids structure
  2457. // with the documents found by query
  2458. assignRawDocsToIdStructure(o.rawIds, o.rawDocs, o.rawOrder, o.options,
  2459. o.localField, o.foreignField);
  2460. // now update the original documents being populated using the
  2461. // result structure that contains real documents.
  2462. var docs = o.docs;
  2463. var rawIds = o.rawIds;
  2464. var options = o.options;
  2465. function setValue(val) {
  2466. return valueFilter(val, options);
  2467. }
  2468. for (var i = 0; i < docs.length; ++i) {
  2469. if (utils.getValue(o.path, docs[i]) == null &&
  2470. !o.originalModel.schema.virtuals[o.path]) {
  2471. continue;
  2472. }
  2473. if (o.isVirtual && !o.justOne && !Array.isArray(rawIds[i])) {
  2474. rawIds[i] = [rawIds[i]];
  2475. }
  2476. utils.setValue(o.path, rawIds[i], docs[i], setValue);
  2477. }
  2478. }
  2479. /*!
  2480. * Assign `vals` returned by mongo query to the `rawIds`
  2481. * structure returned from utils.getVals() honoring
  2482. * query sort order if specified by user.
  2483. *
  2484. * This can be optimized.
  2485. *
  2486. * Rules:
  2487. *
  2488. * if the value of the path is not an array, use findOne rules, else find.
  2489. * for findOne the results are assigned directly to doc path (including null results).
  2490. * for find, if user specified sort order, results are assigned directly
  2491. * else documents are put back in original order of array if found in results
  2492. *
  2493. * @param {Array} rawIds
  2494. * @param {Array} vals
  2495. * @param {Boolean} sort
  2496. * @api private
  2497. */
  2498. function assignRawDocsToIdStructure(rawIds, resultDocs, resultOrder, options, localFields, foreignFields, recursed) {
  2499. // honor user specified sort order
  2500. var newOrder = [];
  2501. var sorting = options.sort && rawIds.length > 1;
  2502. var doc;
  2503. var sid;
  2504. var id;
  2505. for (var i = 0; i < rawIds.length; ++i) {
  2506. id = rawIds[i];
  2507. if (Array.isArray(id)) {
  2508. // handle [ [id0, id2], [id3] ]
  2509. assignRawDocsToIdStructure(id, resultDocs, resultOrder, options, localFields, foreignFields, true);
  2510. newOrder.push(id);
  2511. continue;
  2512. }
  2513. if (id === null && !sorting) {
  2514. // keep nulls for findOne unless sorting, which always
  2515. // removes them (backward compat)
  2516. newOrder.push(id);
  2517. continue;
  2518. }
  2519. sid = String(id);
  2520. if (recursed) {
  2521. // apply find behavior
  2522. // assign matching documents in original order unless sorting
  2523. doc = resultDocs[sid];
  2524. if (doc) {
  2525. if (sorting) {
  2526. newOrder[resultOrder[sid]] = doc;
  2527. } else {
  2528. newOrder.push(doc);
  2529. }
  2530. } else {
  2531. newOrder.push(id);
  2532. }
  2533. } else {
  2534. // apply findOne behavior - if document in results, assign, else assign null
  2535. newOrder[i] = doc = resultDocs[sid] || null;
  2536. }
  2537. }
  2538. rawIds.length = 0;
  2539. if (newOrder.length) {
  2540. // reassign the documents based on corrected order
  2541. // forEach skips over sparse entries in arrays so we
  2542. // can safely use this to our advantage dealing with sorted
  2543. // result sets too.
  2544. newOrder.forEach(function(doc, i) {
  2545. if (!doc) {
  2546. return;
  2547. }
  2548. rawIds[i] = doc;
  2549. });
  2550. }
  2551. }
  2552. function getModelsMapForPopulate(model, docs, options) {
  2553. var i, doc, len = docs.length,
  2554. available = {},
  2555. map = [],
  2556. modelNameFromQuery = options.model && options.model.modelName || options.model,
  2557. schema, refPath, Model, currentOptions, modelNames, modelName, discriminatorKey, modelForFindSchema;
  2558. var originalOptions = utils.clone(options);
  2559. var isVirtual = false;
  2560. schema = model._getSchema(options.path);
  2561. if (schema && schema.caster) {
  2562. schema = schema.caster;
  2563. }
  2564. if (!schema && model.discriminators) {
  2565. discriminatorKey = model.schema.discriminatorMapping.key;
  2566. }
  2567. refPath = schema && schema.options && schema.options.refPath;
  2568. for (i = 0; i < len; i++) {
  2569. doc = docs[i];
  2570. if (refPath) {
  2571. modelNames = utils.getValue(refPath, doc);
  2572. } else {
  2573. if (!modelNameFromQuery) {
  2574. var modelForCurrentDoc = model;
  2575. var schemaForCurrentDoc;
  2576. if (!schema && discriminatorKey) {
  2577. modelForFindSchema = utils.getValue(discriminatorKey, doc);
  2578. if (modelForFindSchema) {
  2579. modelForCurrentDoc = model.db.model(modelForFindSchema);
  2580. schemaForCurrentDoc = modelForCurrentDoc._getSchema(options.path);
  2581. if (schemaForCurrentDoc && schemaForCurrentDoc.caster) {
  2582. schemaForCurrentDoc = schemaForCurrentDoc.caster;
  2583. }
  2584. }
  2585. } else {
  2586. schemaForCurrentDoc = schema;
  2587. }
  2588. var virtual = modelForCurrentDoc.schema.virtuals[options.path];
  2589. if (schemaForCurrentDoc && schemaForCurrentDoc.options && schemaForCurrentDoc.options.ref) {
  2590. modelNames = [schemaForCurrentDoc.options.ref];
  2591. } else if (virtual && virtual.options && virtual.options.ref) {
  2592. modelNames = [virtual && virtual.options && virtual.options.ref];
  2593. isVirtual = true;
  2594. } else {
  2595. modelNames = [model.modelName];
  2596. }
  2597. } else {
  2598. modelNames = [modelNameFromQuery]; // query options
  2599. }
  2600. }
  2601. if (!modelNames) {
  2602. continue;
  2603. }
  2604. if (!Array.isArray(modelNames)) {
  2605. modelNames = [modelNames];
  2606. }
  2607. virtual = model.schema.virtuals[options.path];
  2608. var localField = virtual && virtual.options ?
  2609. virtual.options.localField :
  2610. options.path;
  2611. var foreignField = virtual && virtual.options ?
  2612. virtual.options.foreignField :
  2613. '_id';
  2614. var justOne = virtual && virtual.options && virtual.options.justOne;
  2615. if (virtual && virtual.options && virtual.options.ref) {
  2616. isVirtual = true;
  2617. }
  2618. var ret = convertTo_id(utils.getValue(localField, doc));
  2619. var id = String(utils.getValue(foreignField, doc));
  2620. options._docs[id] = Array.isArray(ret) ? ret.slice() : ret;
  2621. if (doc.$__) {
  2622. doc.populated(options.path, options._docs[id], options);
  2623. }
  2624. var k = modelNames.length;
  2625. while (k--) {
  2626. modelName = modelNames[k];
  2627. Model = originalOptions.model && originalOptions.model.modelName ?
  2628. originalOptions.model :
  2629. model.db.model(modelName);
  2630. if (!available[modelName]) {
  2631. currentOptions = {
  2632. model: Model
  2633. };
  2634. utils.merge(currentOptions, options);
  2635. if (schema && !discriminatorKey) {
  2636. currentOptions.model = Model;
  2637. }
  2638. options.model = Model;
  2639. available[modelName] = {
  2640. Model: Model,
  2641. options: currentOptions,
  2642. docs: [doc],
  2643. ids: [ret],
  2644. // Assume only 1 localField + foreignField
  2645. localField: localField,
  2646. foreignField: foreignField,
  2647. justOne: justOne,
  2648. isVirtual: isVirtual
  2649. };
  2650. map.push(available[modelName]);
  2651. } else {
  2652. available[modelName].docs.push(doc);
  2653. available[modelName].ids.push(ret);
  2654. }
  2655. }
  2656. }
  2657. return map;
  2658. }
  2659. /*!
  2660. * Retrieve the _id of `val` if a Document or Array of Documents.
  2661. *
  2662. * @param {Array|Document|Any} val
  2663. * @return {Array|Document|Any}
  2664. */
  2665. function convertTo_id(val) {
  2666. if (val instanceof Model) return val._id;
  2667. if (Array.isArray(val)) {
  2668. for (var i = 0; i < val.length; ++i) {
  2669. if (val[i] instanceof Model) {
  2670. val[i] = val[i]._id;
  2671. }
  2672. }
  2673. return val;
  2674. }
  2675. return val;
  2676. }
  2677. /*!
  2678. * 1) Apply backwards compatible find/findOne behavior to sub documents
  2679. *
  2680. * find logic:
  2681. * a) filter out non-documents
  2682. * b) remove _id from sub docs when user specified
  2683. *
  2684. * findOne
  2685. * a) if no doc found, set to null
  2686. * b) remove _id from sub docs when user specified
  2687. *
  2688. * 2) Remove _ids when specified by users query.
  2689. *
  2690. * background:
  2691. * _ids are left in the query even when user excludes them so
  2692. * that population mapping can occur.
  2693. */
  2694. function valueFilter(val, assignmentOpts) {
  2695. if (Array.isArray(val)) {
  2696. // find logic
  2697. var ret = [];
  2698. var numValues = val.length;
  2699. for (var i = 0; i < numValues; ++i) {
  2700. var subdoc = val[i];
  2701. if (!isDoc(subdoc)) continue;
  2702. maybeRemoveId(subdoc, assignmentOpts);
  2703. ret.push(subdoc);
  2704. if (assignmentOpts.originalLimit &&
  2705. ret.length >= assignmentOpts.originalLimit) {
  2706. break;
  2707. }
  2708. }
  2709. // Since we don't want to have to create a new mongoosearray, make sure to
  2710. // modify the array in place
  2711. while (val.length > ret.length) {
  2712. Array.prototype.pop.apply(val, []);
  2713. }
  2714. for (i = 0; i < ret.length; ++i) {
  2715. val[i] = ret[i];
  2716. }
  2717. return val;
  2718. }
  2719. // findOne
  2720. if (isDoc(val)) {
  2721. maybeRemoveId(val, assignmentOpts);
  2722. return val;
  2723. }
  2724. return null;
  2725. }
  2726. /*!
  2727. * Remove _id from `subdoc` if user specified "lean" query option
  2728. */
  2729. function maybeRemoveId(subdoc, assignmentOpts) {
  2730. if (assignmentOpts.excludeId) {
  2731. if (typeof subdoc.setValue === 'function') {
  2732. delete subdoc._doc._id;
  2733. } else {
  2734. delete subdoc._id;
  2735. }
  2736. }
  2737. }
  2738. /*!
  2739. * Determine if `doc` is a document returned
  2740. * by a populate query.
  2741. */
  2742. function isDoc(doc) {
  2743. if (doc == null) {
  2744. return false;
  2745. }
  2746. var type = typeof doc;
  2747. if (type === 'string') {
  2748. return false;
  2749. }
  2750. if (type === 'number') {
  2751. return false;
  2752. }
  2753. if (Buffer.isBuffer(doc)) {
  2754. return false;
  2755. }
  2756. if (doc.constructor.name === 'ObjectID') {
  2757. return false;
  2758. }
  2759. // only docs
  2760. return true;
  2761. }
  2762. /**
  2763. * Finds the schema for `path`. This is different than
  2764. * calling `schema.path` as it also resolves paths with
  2765. * positional selectors (something.$.another.$.path).
  2766. *
  2767. * @param {String} path
  2768. * @return {Schema}
  2769. * @api private
  2770. */
  2771. Model._getSchema = function _getSchema(path) {
  2772. return this.schema._getSchema(path);
  2773. };
  2774. /*!
  2775. * Compiler utility.
  2776. *
  2777. * @param {String} name model name
  2778. * @param {Schema} schema
  2779. * @param {String} collectionName
  2780. * @param {Connection} connection
  2781. * @param {Mongoose} base mongoose instance
  2782. */
  2783. Model.compile = function compile(name, schema, collectionName, connection, base) {
  2784. var versioningEnabled = schema.options.versionKey !== false;
  2785. if (versioningEnabled && !schema.paths[schema.options.versionKey]) {
  2786. // add versioning to top level documents only
  2787. var o = {};
  2788. o[schema.options.versionKey] = Number;
  2789. schema.add(o);
  2790. }
  2791. // generate new class
  2792. function model(doc, fields, skipId) {
  2793. if (!(this instanceof model)) {
  2794. return new model(doc, fields, skipId);
  2795. }
  2796. Model.call(this, doc, fields, skipId);
  2797. }
  2798. model.hooks = schema.s.hooks.clone();
  2799. model.base = base;
  2800. model.modelName = name;
  2801. model.__proto__ = Model;
  2802. model.prototype.__proto__ = Model.prototype;
  2803. model.model = Model.prototype.model;
  2804. model.db = model.prototype.db = connection;
  2805. model.discriminators = model.prototype.discriminators = undefined;
  2806. model.prototype.$__setSchema(schema);
  2807. var collectionOptions = {
  2808. bufferCommands: schema.options.bufferCommands,
  2809. capped: schema.options.capped
  2810. };
  2811. model.prototype.collection = connection.collection(
  2812. collectionName
  2813. , collectionOptions
  2814. );
  2815. // apply methods and statics
  2816. applyMethods(model, schema);
  2817. applyStatics(model, schema);
  2818. model.schema = model.prototype.schema;
  2819. model.collection = model.prototype.collection;
  2820. // Create custom query constructor
  2821. model.Query = function() {
  2822. Query.apply(this, arguments);
  2823. };
  2824. model.Query.prototype = Object.create(Query.prototype);
  2825. model.Query.base = Query.base;
  2826. applyQueryMethods(model, schema.query);
  2827. var kareemOptions = { useErrorHandlers: true };
  2828. model.$__insertMany = model.hooks.createWrapper('insertMany',
  2829. model.insertMany, model, kareemOptions);
  2830. model.insertMany = function(arr, callback) {
  2831. var Promise = PromiseProvider.get();
  2832. return new Promise.ES6(function(resolve, reject) {
  2833. model.$__insertMany(arr, function(error, result) {
  2834. if (error) {
  2835. callback && callback(error);
  2836. return reject(error);
  2837. }
  2838. callback && callback(null, result);
  2839. resolve(result);
  2840. });
  2841. });
  2842. };
  2843. return model;
  2844. };
  2845. /*!
  2846. * Register methods for this model
  2847. *
  2848. * @param {Model} model
  2849. * @param {Schema} schema
  2850. */
  2851. var applyMethods = function(model, schema) {
  2852. function apply(method, schema) {
  2853. Object.defineProperty(model.prototype, method, {
  2854. get: function() {
  2855. var h = {};
  2856. for (var k in schema.methods[method]) {
  2857. h[k] = schema.methods[method][k].bind(this);
  2858. }
  2859. return h;
  2860. },
  2861. configurable: true
  2862. });
  2863. }
  2864. for (var method in schema.methods) {
  2865. if (typeof schema.methods[method] === 'function') {
  2866. model.prototype[method] = schema.methods[method];
  2867. } else {
  2868. apply(method, schema);
  2869. }
  2870. }
  2871. };
  2872. /*!
  2873. * Register statics for this model
  2874. * @param {Model} model
  2875. * @param {Schema} schema
  2876. */
  2877. var applyStatics = function(model, schema) {
  2878. for (var i in schema.statics) {
  2879. model[i] = schema.statics[i];
  2880. }
  2881. };
  2882. /*!
  2883. * Register custom query methods for this model
  2884. *
  2885. * @param {Model} model
  2886. * @param {Schema} schema
  2887. */
  2888. function applyQueryMethods(model, methods) {
  2889. for (var i in methods) {
  2890. model.Query.prototype[i] = methods[i];
  2891. }
  2892. }
  2893. /*!
  2894. * Subclass this model with `conn`, `schema`, and `collection` settings.
  2895. *
  2896. * @param {Connection} conn
  2897. * @param {Schema} [schema]
  2898. * @param {String} [collection]
  2899. * @return {Model}
  2900. */
  2901. Model.__subclass = function subclass(conn, schema, collection) {
  2902. // subclass model using this connection and collection name
  2903. var _this = this;
  2904. var Model = function Model(doc, fields, skipId) {
  2905. if (!(this instanceof Model)) {
  2906. return new Model(doc, fields, skipId);
  2907. }
  2908. _this.call(this, doc, fields, skipId);
  2909. };
  2910. Model.__proto__ = _this;
  2911. Model.prototype.__proto__ = _this.prototype;
  2912. Model.db = Model.prototype.db = conn;
  2913. var s = schema && typeof schema !== 'string'
  2914. ? schema
  2915. : _this.prototype.schema;
  2916. var options = s.options || {};
  2917. if (!collection) {
  2918. collection = _this.prototype.schema.get('collection')
  2919. || utils.toCollectionName(_this.modelName, options);
  2920. }
  2921. var collectionOptions = {
  2922. bufferCommands: s ? options.bufferCommands : true,
  2923. capped: s && options.capped
  2924. };
  2925. Model.prototype.collection = conn.collection(collection, collectionOptions);
  2926. Model.collection = Model.prototype.collection;
  2927. Model.init();
  2928. return Model;
  2929. };
  2930. Model.$wrapCallback = function(callback) {
  2931. var _this = this;
  2932. return function() {
  2933. try {
  2934. callback.apply(null, arguments);
  2935. } catch (error) {
  2936. _this.emit('error', error);
  2937. }
  2938. };
  2939. };
  2940. /*!
  2941. * Module exports.
  2942. */
  2943. module.exports = exports = Model;