Skip to content

Different timestamp behaviour for different operators on nested subdocuments #12119

@lx-0

Description

@lx-0

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Mongoose version

6.3.3

Node.js version

12

MongoDB server version

4.5

Description

When updating a nested document array, the timestamps of the nested documents are only updated in certain cases.

When using findOneAndUpdate and updating the nested document via $set operator, the timestamps are not updated in certain cases even if the timestamps option is enabled on the child schema.

Automatic update of the timestamps on the deepest schema only works if either all nodes in-between have option timestamp: true OR when using the $push operator.

This is due to function applyTimestampsToSingleNested (and respectively applyTimestampsToDocumentArray) exiting too early when the timestamp option on the current node is not set, ignoring all child nodes from there.

  import mongoose from "mongoose";

  // `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: {
      type: [ConditionSchema],
    },
  });

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

  const User = mongoose.model("User", UserSchema);

Steps to Reproduce

// $set does not update timestamps when inserting / replacing whole node
User.findOneAndUpdate(
          { name: 'Xyz' },
          { $set: { profile: {conditions: [{ kind: 'price', amount: 10 }] } } },
);
// $push does update timestamps when inserting to node
User.findOneAndUpdate(
          { name: 'Xyz' },
          { $push: { 'profile.conditions': { kind: 'price', amount: 10 } } },
);

Expected Behavior

Timestamps should also update on nested subdocuments.

Metadata

Metadata

Assignees

No one assigned

    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