UNPKG

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