Search code examples
node.jsdatabasemongodbmongoosebackend

How can I add timestamps to the nested Schema in mongoose?


This is how my mongoose model looks like, I have a comment Schema and it has replies field which can be an array of objects of the same type.

const commentSchema = new Schema({
  body: {
    type: String,
    required: true
  },
  likes: {
    type: Number,
    default: 0,
  },
  wroteBy: {
    type: Schema.Types.ObjectId,
    ref: 'User'
  },
  replies: [this]
}, { timestamps: true })

Default timestamps work fine for the main object, however comments in the replies array don't get any timestamps.

Thanks for any help!


Solution

  • You need to specify timestamp option also in reply schema definition.

    const replySchema = new Schema({
      body: {
        type: String,
        required: true
      },
      likes: {
        type: Number,
        default: 0,
      },
      wroteBy: {
        type: Schema.Types.ObjectId,
        ref: 'User'
      },
    }, { timestamps: true }); // <<<--- Add timestamp to reply schema
    
    const commentSchema = new Schema({
      body: {
        type: String,
        required: true
      },
      likes: {
        type: Number,
        default: 0,
      },
      wroteBy: {
        type: Schema.Types.ObjectId,
        ref: 'User'
      },
      replies: [replySchema]
    }, { timestamps: true });