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