-
-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
castUpdate.js
353 lines (310 loc) · 8.84 KB
/
castUpdate.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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
'use strict';
var StrictModeError = require('../../error/strict');
var ValidationError = require('../../error/validation');
var utils = require('../../utils');
/*!
* Casts an update op based on the given schema
*
* @param {Schema} schema
* @param {Object} obj
* @param {Object} options
* @param {Boolean} [options.overwrite] defaults to false
* @param {Boolean|String} [options.strict] defaults to true
* @param {Query} context passed to setters
* @return {Boolean} true iff the update is non-empty
*/
module.exports = function castUpdate(schema, obj, options, context) {
if (!obj) {
return undefined;
}
var ops = Object.keys(obj);
var i = ops.length;
var ret = {};
var hasKeys;
var val;
var hasDollarKey = false;
var overwrite = options.overwrite;
while (i--) {
var op = ops[i];
// if overwrite is set, don't do any of the special $set stuff
if (op[0] !== '$' && !overwrite) {
// fix up $set sugar
if (!ret.$set) {
if (obj.$set) {
ret.$set = obj.$set;
} else {
ret.$set = {};
}
}
ret.$set[op] = obj[op];
ops.splice(i, 1);
if (!~ops.indexOf('$set')) ops.push('$set');
} else if (op === '$set') {
if (!ret.$set) {
ret[op] = obj[op];
}
} else {
ret[op] = obj[op];
}
}
// cast each value
i = ops.length;
// if we get passed {} for the update, we still need to respect that when it
// is an overwrite scenario
if (overwrite) {
hasKeys = true;
}
while (i--) {
op = ops[i];
val = ret[op];
hasDollarKey = hasDollarKey || op.charAt(0) === '$';
if (val &&
typeof val === 'object' &&
(!overwrite || hasDollarKey)) {
hasKeys |= walkUpdatePath(schema, val, op, options.strict, context);
} else if (overwrite && ret && typeof ret === 'object') {
// if we are just using overwrite, cast the query and then we will
// *always* return the value, even if it is an empty object. We need to
// set hasKeys above because we need to account for the case where the
// user passes {} and wants to clobber the whole document
// Also, _walkUpdatePath expects an operation, so give it $set since that
// is basically what we're doing
walkUpdatePath(schema, ret, '$set', options.strict, context);
} else {
var msg = 'Invalid atomic update value for ' + op + '. '
+ 'Expected an object, received ' + typeof val;
throw new Error(msg);
}
}
return hasKeys && ret;
};
/*!
* Walk each path of obj and cast its values
* according to its schema.
*
* @param {Schema} schema
* @param {Object} obj - part of a query
* @param {String} op - the atomic operator ($pull, $set, etc)
* @param {Boolean|String} strict
* @param {Query} context
* @param {String} pref - path prefix (internal only)
* @return {Bool} true if this path has keys to update
* @api private
*/
function walkUpdatePath(schema, obj, op, strict, context, pref) {
var prefix = pref ? pref + '.' : '';
var keys = Object.keys(obj);
var i = keys.length;
var hasKeys = false;
var schematype;
var key;
var val;
var hasError = false;
var aggregatedError = new ValidationError();
var useNestedStrict = schema.options.useNestedStrict;
while (i--) {
key = keys[i];
val = obj[key];
if (val && val.constructor.name === 'Object') {
// watch for embedded doc schemas
schematype = schema._getSchema(prefix + key);
if (schematype && schematype.caster && op in castOps) {
// embedded doc schema
hasKeys = true;
if ('$each' in val) {
try {
obj[key] = {
$each: castUpdateVal(schematype, val.$each, op, context)
};
} catch (error) {
hasError = true;
_handleCastError(error, context, key, aggregatedError);
}
if (val.$slice != null) {
obj[key].$slice = val.$slice | 0;
}
if (val.$sort) {
obj[key].$sort = val.$sort;
}
if (!!val.$position || val.$position === 0) {
obj[key].$position = val.$position;
}
} else {
try {
obj[key] = castUpdateVal(schematype, val, op, context);
} catch (error) {
hasError = true;
_handleCastError(error, context, key, aggregatedError);
}
}
} else if ((op === '$currentDate') || (op in castOps && schematype)) {
// $currentDate can take an object
try {
obj[key] = castUpdateVal(schematype, val, op, context);
} catch (error) {
hasError = true;
_handleCastError(error, context, key, aggregatedError);
}
hasKeys = true;
} else {
var pathToCheck = (prefix + key);
var v = schema._getPathType(pathToCheck);
var _strict = strict;
if (useNestedStrict &&
v &&
v.schema &&
'strict' in v.schema.options) {
_strict = v.schema.options.strict;
}
if (v.pathType === 'undefined') {
if (_strict === 'throw') {
throw new StrictModeError(pathToCheck);
} else if (_strict) {
delete obj[key];
continue;
}
}
// gh-2314
// we should be able to set a schema-less field
// to an empty object literal
hasKeys |= walkUpdatePath(schema, val, op, strict, context, prefix + key) ||
(utils.isObject(val) && Object.keys(val).length === 0);
}
} else {
var checkPath = (key === '$each' || key === '$or' || key === '$and') ?
pref : prefix + key;
schematype = schema._getSchema(checkPath);
var pathDetails = schema._getPathType(checkPath);
var isStrict = strict;
if (useNestedStrict &&
pathDetails &&
pathDetails.schema &&
'strict' in pathDetails.schema.options) {
isStrict = pathDetails.schema.options.strict;
}
var skip = isStrict &&
!schematype &&
!/real|nested/.test(pathDetails.pathType);
if (skip) {
if (isStrict === 'throw') {
throw new StrictModeError(prefix + key);
} else {
delete obj[key];
}
} else {
// gh-1845 temporary fix: ignore $rename. See gh-3027 for tracking
// improving this.
if (op === '$rename') {
hasKeys = true;
continue;
}
hasKeys = true;
try {
obj[key] = castUpdateVal(schematype, val, op, key, context);
} catch (error) {
hasError = true;
_handleCastError(error, context, key, aggregatedError);
}
}
}
}
if (hasError) {
throw aggregatedError;
}
return hasKeys;
}
/*!
* ignore
*/
function _handleCastError(error, query, key, aggregatedError) {
if (typeof query !== 'object' || !query.options.multipleCastError) {
throw error;
}
aggregatedError.addError(key, error);
}
/*!
* These operators should be cast to numbers instead
* of their path schema type.
*/
var numberOps = {
$pop: 1,
$unset: 1,
$inc: 1
};
/*!
* These operators require casting docs
* to real Documents for Update operations.
*/
var castOps = {
$push: 1,
$addToSet: 1,
$set: 1,
$setOnInsert: 1
};
/*!
* ignore
*/
var overwriteOps = {
$set: 1,
$setOnInsert: 1
};
/*!
* Casts `val` according to `schema` and atomic `op`.
*
* @param {SchemaType} schema
* @param {Object} val
* @param {String} op - the atomic operator ($pull, $set, etc)
* @param {String} $conditional
* @param {Query} context
* @api private
*/
function castUpdateVal(schema, val, op, $conditional, context) {
if (!schema) {
// non-existing schema path
return op in numberOps
? Number(val)
: val;
}
var cond = schema.caster && op in castOps &&
(utils.isObject(val) || Array.isArray(val));
if (cond) {
// Cast values for ops that add data to MongoDB.
// Ensures embedded documents get ObjectIds etc.
var tmp = schema.cast(val);
if (Array.isArray(val)) {
val = tmp;
} else if (Array.isArray(tmp)) {
val = tmp[0];
} else {
val = tmp;
}
return val;
}
if (op in numberOps) {
if (op === '$inc') {
return schema.castForQueryWrapper({ val: val, context: context });
}
return Number(val);
}
if (op === '$currentDate') {
if (typeof val === 'object') {
return {$type: val.$type};
}
return Boolean(val);
}
if (/^\$/.test($conditional)) {
return schema.castForQueryWrapper({
$conditional: $conditional,
val: val,
context: context
});
}
if (overwriteOps[op]) {
return schema.castForQueryWrapper({
val: val,
context: context,
$skipQueryCastForUpdate: val != null && schema.$isMongooseArray
});
}
return schema.castForQueryWrapper({ val: val, context: context });
}