Skip to content

Commit 66fd25f

Browse files
committedJul 16, 2021
fix(timestamps): apply timestamps when creating new subdocs with $addToSet and with positional operator
Fix #10447
1 parent c6a646c commit 66fd25f

File tree

1 file changed

+35
-28
lines changed

1 file changed

+35
-28
lines changed
 

‎lib/helpers/update/applyTimestampsToChildren.js

+35-28
Original file line numberDiff line numberDiff line change
@@ -19,34 +19,10 @@ function applyTimestampsToChildren(now, update, schema) {
1919

2020
if (hasDollarKey) {
2121
if (update.$push) {
22-
for (const key of Object.keys(update.$push)) {
23-
const $path = schema.path(key);
24-
if (update.$push[key] &&
25-
$path &&
26-
$path.$isMongooseDocumentArray &&
27-
$path.schema.options.timestamps) {
28-
const timestamps = $path.schema.options.timestamps;
29-
const createdAt = handleTimestampOption(timestamps, 'createdAt');
30-
const updatedAt = handleTimestampOption(timestamps, 'updatedAt');
31-
if (update.$push[key].$each) {
32-
update.$push[key].$each.forEach(function(subdoc) {
33-
if (updatedAt != null) {
34-
subdoc[updatedAt] = now;
35-
}
36-
if (createdAt != null) {
37-
subdoc[createdAt] = now;
38-
}
39-
});
40-
} else {
41-
if (updatedAt != null) {
42-
update.$push[key][updatedAt] = now;
43-
}
44-
if (createdAt != null) {
45-
update.$push[key][createdAt] = now;
46-
}
47-
}
48-
}
49-
}
22+
_applyTimestampToUpdateOperator(update.$push);
23+
}
24+
if (update.$addToSet) {
25+
_applyTimestampToUpdateOperator(update.$addToSet);
5026
}
5127
if (update.$set != null) {
5228
const keys = Object.keys(update.$set);
@@ -60,6 +36,37 @@ function applyTimestampsToChildren(now, update, schema) {
6036
for (const key of updateKeys) {
6137
applyTimestampsToUpdateKey(schema, key, update, now);
6238
}
39+
40+
function _applyTimestampToUpdateOperator(op) {
41+
for (const key of Object.keys(op)) {
42+
const $path = schema.path(key.replace(/\.\$\./i, '.').replace(/.\$$/, ''));
43+
if (op[key] &&
44+
$path &&
45+
$path.$isMongooseDocumentArray &&
46+
$path.schema.options.timestamps) {
47+
const timestamps = $path.schema.options.timestamps;
48+
const createdAt = handleTimestampOption(timestamps, 'createdAt');
49+
const updatedAt = handleTimestampOption(timestamps, 'updatedAt');
50+
if (op[key].$each) {
51+
op[key].$each.forEach(function(subdoc) {
52+
if (updatedAt != null) {
53+
subdoc[updatedAt] = now;
54+
}
55+
if (createdAt != null) {
56+
subdoc[createdAt] = now;
57+
}
58+
});
59+
} else {
60+
if (updatedAt != null) {
61+
op[key][updatedAt] = now;
62+
}
63+
if (createdAt != null) {
64+
op[key][createdAt] = now;
65+
}
66+
}
67+
}
68+
}
69+
}
6370
}
6471

6572
function applyTimestampsToDocumentArray(arr, schematype, now) {

0 commit comments

Comments
 (0)
Please sign in to comment.