document.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. 'use strict';
  2. var _ = require('lodash');
  3. /**
  4. * Document constructor.
  5. *
  6. * @class
  7. * @param {object} data
  8. */
  9. function Document(data) {
  10. if (data) {
  11. var keys = Object.keys(data);
  12. var key;
  13. for (var i = 0, len = keys.length; i < len; i++) {
  14. key = keys[i];
  15. this[key] = data[key];
  16. }
  17. }
  18. }
  19. /**
  20. * Saves the document.
  21. *
  22. * @param {function} [callback]
  23. * @return {Promise}
  24. */
  25. Document.prototype.save = function(callback) {
  26. return this._model.save(this, callback);
  27. };
  28. /**
  29. * Updates the document.
  30. *
  31. * @param {object} data
  32. * @param {function} [callback]
  33. * @return {Promise}
  34. */
  35. Document.prototype.update = function(data, callback) {
  36. return this._model.updateById(this._id, data, callback);
  37. };
  38. /**
  39. * Replaces the document.
  40. *
  41. * @param {object} data
  42. * @param {function} [callback]
  43. * @return {Promise}
  44. */
  45. Document.prototype.replace = function(data, callback) {
  46. return this._model.replaceById(this._id, data, callback);
  47. };
  48. /**
  49. * Removes the document.
  50. *
  51. * @param {function} [callback]
  52. * @return {Promise}
  53. */
  54. Document.prototype.remove = function(callback) {
  55. return this._model.removeById(this._id, callback);
  56. };
  57. /**
  58. * Returns a plain JavaScript object.
  59. *
  60. * @return {object}
  61. */
  62. Document.prototype.toObject = function() {
  63. var keys = Object.keys(this);
  64. var obj = {};
  65. var key;
  66. for (var i = 0, len = keys.length; i < len; i++) {
  67. key = keys[i];
  68. // Don't deep clone getters in order to avoid "Maximum call stack size
  69. // exceeded" error
  70. obj[key] = isGetter(this, key) ? this[key] : _.cloneDeep(this[key]);
  71. }
  72. return obj;
  73. };
  74. function isGetter(obj, key) {
  75. return Object.getOwnPropertyDescriptor(obj, key).get;
  76. }
  77. /**
  78. * Returns a string representing the document.
  79. *
  80. * @return {String}
  81. */
  82. Document.prototype.toString = function() {
  83. return JSON.stringify(this);
  84. };
  85. /**
  86. * Populates document references.
  87. *
  88. * @param {String|Object} expr
  89. * @return {Document}
  90. */
  91. Document.prototype.populate = function(expr) {
  92. var stack = this._schema._parsePopulate(expr);
  93. return this._model._populate(this, stack);
  94. };
  95. module.exports = Document;