blob: 36b87d776eefda3a6bc48aa99c09e2f17b2eb16a (
plain)
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
|
'use strict';
var modifiedPaths = require('./common').modifiedPaths;
/**
* Applies defaults to update and findOneAndUpdate operations.
*
* @param {Query} query
* @param {Schema} schema
* @param {Object} castedDoc
* @param {Object} options
* @method setDefaultsOnInsert
* @api private
*/
module.exports = function(query, schema, castedDoc, options) {
var keys = Object.keys(castedDoc || {});
var updatedKeys = {};
var updatedValues = {};
var numKeys = keys.length;
var hasDollarUpdate = false;
var modified = {};
if (options && options.upsert) {
for (var i = 0; i < numKeys; ++i) {
if (keys[i].charAt(0) === '$') {
modifiedPaths(castedDoc[keys[i]], '', modified);
hasDollarUpdate = true;
}
}
if (!hasDollarUpdate) {
modifiedPaths(castedDoc, '', modified);
}
var paths = Object.keys(query._conditions);
var numPaths = keys.length;
for (i = 0; i < numPaths; ++i) {
var path = paths[i];
var condition = query._conditions[path];
if (condition && typeof condition === 'object') {
var conditionKeys = Object.keys(condition);
var numConditionKeys = conditionKeys.length;
var hasDollarKey = false;
for (var j = 0; j < numConditionKeys; ++j) {
if (conditionKeys[j].charAt(0) === '$') {
hasDollarKey = true;
break;
}
}
if (hasDollarKey) {
continue;
}
}
updatedKeys[path] = true;
modified[path] = true;
}
if (options.setDefaultsOnInsert) {
schema.eachPath(function(path, schemaType) {
if (path === '_id') {
// Ignore _id for now because it causes bugs in 2.4
return;
}
if (schemaType.$isSingleNested) {
// Only handle nested schemas 1-level deep to avoid infinite
// recursion re: https://github.com/mongodb-js/mongoose-autopopulate/issues/11
schemaType.schema.eachPath(function(_path, _schemaType) {
if (path === '_id') {
// Ignore _id for now because it causes bugs in 2.4
return;
}
var def = _schemaType.getDefault(null, true);
if (!modified[path + '.' + _path] && typeof def !== 'undefined') {
castedDoc = castedDoc || {};
castedDoc.$setOnInsert = castedDoc.$setOnInsert || {};
castedDoc.$setOnInsert[path + '.' + _path] = def;
updatedValues[path + '.' + _path] = def;
}
});
} else {
var def = schemaType.getDefault(null, true);
if (!modified[path] && typeof def !== 'undefined') {
castedDoc = castedDoc || {};
castedDoc.$setOnInsert = castedDoc.$setOnInsert || {};
castedDoc.$setOnInsert[path] = def;
updatedValues[path] = def;
}
}
});
}
}
return castedDoc;
};
|