Automattic / mongoose

MongoDB object modeling designed to work in an asynchronous environment.
https://mongoosejs.com
MIT License
26.96k stars 3.84k forks source link

Docs: Need to mention that `createdAt` uses `this._id.getTimestamp()` #11182

Closed niftylettuce closed 2 years ago

niftylettuce commented 2 years ago

Docs should mention that createdAt uses this._id.getTimestamp() here https://mongoosejs.com/docs/guide.html#timestamps, and instead might be confusing as the reader would think it uses the current time.

Internally we can see that Mongoose uses this here:

node_modules/mongoose/lib/helpers/timestamps/setupTimestamps.js
20:  const createdAt = handleTimestampOption(timestamps, 'createdAt');
27:  schema.$timestamps = { createdAt: createdAt, updatedAt: updatedAt };
33:  if (createdAt && !schema.paths[createdAt]) {
34:    schemaAdditions[createdAt] = { [schema.options.typeKey || 'type']: Date, immutable: true };
45:    const skipCreatedAt = timestampOption != null && timestampOption.createdAt === false;
52:    if (!skipCreatedAt && this.isNew && createdAt && !this.$__getValue(createdAt) && this.$__isSelected(createdAt)) {
53:      this.$set(createdAt, auto_id ? this._id.getTimestamp() : defaultTimestamp);
59:        if (createdAt != null) {
60:          ts = this.$__getValue(createdAt);
75:    if (createdAt && !this.get(createdAt)) {
76:      this.$set(createdAt, ts);
102:    applyTimestampsToUpdate(now, createdAt, updatedAt, this.getUpdate(),

Via this._id.getTimestamp()

vkarpov15 commented 2 years ago

I took a closer look and it doesn't look like Mongoose 6 ever uses getTimestamps(). https://github.com/Automattic/mongoose/blob/1e6ccc55d93a1f4f5a2822a9afed305a173f996a/lib/helpers/timestamps/setupTimestamps.js#L50 is always false because this is a document, not a schema, in that line. So unless the ObjectId happens to have an auto property, we'll always use defaultTimestamp.

We'll get rid of that code since it is dead for practical purposes.