1 | 'use strict';
|
2 |
|
3 | const cloneDeep = require('rfdc')();
|
4 |
|
5 | class Document {
|
6 |
|
7 | |
8 |
|
9 |
|
10 |
|
11 |
|
12 | constructor(data) {
|
13 | if (data) {
|
14 | Object.assign(this, data);
|
15 | }
|
16 | }
|
17 |
|
18 | |
19 |
|
20 |
|
21 |
|
22 |
|
23 |
|
24 | save(callback) {
|
25 | return this._model.save(this, callback);
|
26 | }
|
27 |
|
28 | |
29 |
|
30 |
|
31 |
|
32 |
|
33 |
|
34 |
|
35 | update(data, callback) {
|
36 | return this._model.updateById(this._id, data, callback);
|
37 | }
|
38 |
|
39 | |
40 |
|
41 |
|
42 |
|
43 |
|
44 |
|
45 |
|
46 | replace(data, callback) {
|
47 | return this._model.replaceById(this._id, data, callback);
|
48 | }
|
49 |
|
50 | |
51 |
|
52 |
|
53 |
|
54 |
|
55 |
|
56 | remove(callback) {
|
57 | return this._model.removeById(this._id, callback);
|
58 | }
|
59 |
|
60 | |
61 |
|
62 |
|
63 |
|
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 |
|
72 |
|
73 | obj[key] = isGetter(this, key) ? this[key] : cloneDeep(this[key]);
|
74 | }
|
75 |
|
76 | return obj;
|
77 | }
|
78 |
|
79 | |
80 |
|
81 |
|
82 |
|
83 |
|
84 | toString() {
|
85 | return JSON.stringify(this);
|
86 | }
|
87 |
|
88 | |
89 |
|
90 |
|
91 |
|
92 |
|
93 |
|
94 | populate(expr) {
|
95 | const stack = this._schema._parsePopulate(expr);
|
96 | return this._model._populate(this, stack);
|
97 | }
|
98 | }
|
99 |
|
100 | function isGetter(obj, key) {
|
101 | return Object.getOwnPropertyDescriptor(obj, key).get;
|
102 | }
|
103 |
|
104 | module.exports = Document;
|