Skip to content

Commit

Permalink
Merge pull request #12151 from Automattic/vkarpov15/gh-12119
Browse files Browse the repository at this point in the history
fix(timestamps): set timestamps on child schema when child schema has timestamps: true but parent schema does not
  • Loading branch information
vkarpov15 committed Jul 27, 2022
2 parents f5ee642 + 77f671a commit 18d683b
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 2 deletions.
8 changes: 6 additions & 2 deletions lib/helpers/update/applyTimestampsToChildren.js
Expand Up @@ -82,12 +82,15 @@ function applyTimestampsToChildren(now, update, schema) {
function applyTimestampsToDocumentArray(arr, schematype, now) {
const timestamps = schematype.schema.options.timestamps;

const len = arr.length;

if (!timestamps) {
for (let i = 0; i < len; ++i) {
applyTimestampsToChildren(now, arr[i], schematype.schema);
}
return;
}

const len = arr.length;

const createdAt = handleTimestampOption(timestamps, 'createdAt');
const updatedAt = handleTimestampOption(timestamps, 'updatedAt');
for (let i = 0; i < len; ++i) {
Expand All @@ -105,6 +108,7 @@ function applyTimestampsToDocumentArray(arr, schematype, now) {
function applyTimestampsToSingleNested(subdoc, schematype, now) {
const timestamps = schematype.schema.options.timestamps;
if (!timestamps) {
applyTimestampsToChildren(now, subdoc, schematype.schema);
return;
}

Expand Down
31 changes: 31 additions & 0 deletions test/timestamps.test.js
Expand Up @@ -964,6 +964,37 @@ describe('timestamps', function() {
assert.ok(updatedParent.child.created instanceof Date);
assert.strictEqual(updatedParent.child.created.valueOf(), date.valueOf());
});

it('sets timestamps on sub-schema if parent schema does not have timestamps: true (gh-12119)', async function() {
// `timestamps` option set to true on deepest sub document
const ConditionSchema = new mongoose.Schema({
kind: String,
amount: Number
}, { timestamps: true });

// no `timestamps` option defined
const ProfileSchema = new mongoose.Schema({
conditions: [ConditionSchema]
});

const UserSchema = new mongoose.Schema({
name: String,
profile: {
type: ProfileSchema
}
}, { timestamps: true });

const User = db.model('User', UserSchema);

const res = await User.findOneAndUpdate(
{ name: 'test' },
{ $set: { profile: { conditions: [{ kind: 'price', amount: 10 }] } } },
{ upsert: true, returnDocument: 'after' }
);

assert.ok(res.profile.conditions[0].createdAt);
assert.ok(res.profile.conditions[0].updatedAt);
});
});

async function delay(ms) {
Expand Down

0 comments on commit 18d683b

Please sign in to comment.