document.js 1.9 KB

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