Skip to content

mongoose timestamps createdAt added to existing documents upon doc.save() #11024

@guy-evdev

Description

@guy-evdev

nodejs version 14.16.0
mongoose version 5.12.5
MongoDB driver (nodejs) 3.6.5

mongoose timestamps configuration:
{timestamps: {createdAt: 'createdAt', updatedAt: 'lut'}}

Steps for reproducing:

  1. Document without the createdAt field (was created before adding timestamps to the schema).
  2. Document retrieved from DB using findOne() with no field projection
  3. Adding/modifying fields
  4. Saving the document using doc.save()
    After saving, the createdAt field is added to the document with the current date which of course is not the expected behavior since the createdAt field should reflect the actual document creation date (which was created much earlier)

It will not happen when:
Using findAndUpdate (much better the findOne and save - I know)
Using findOne with field projection

As a temporary workaround, I added the following to all schemas using timestamps
createdAt: {type: Date, select: false}
When the above is added, the createdAt field is not added to the existing document upon saving but this is definitely intended as a quick-fix and not a permanent solution since the expected behaviour is that the createdAt field will not be added to an existing document if not specifically requested.

Metadata

Metadata

Assignees

Labels

confirmed-bugWe've confirmed this is a bug in Mongoose and will fix it.

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions