Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(timestamps): set timestamps on child schema when child schema has timestamps: true but parent schema does not #12151

Merged
merged 1 commit into from Jul 27, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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