You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Mongoose中的嵌套Schema添加时间戳?

解决Mongoose嵌套评论(replies)无时间戳问题

问题根源在于:使用replies: [this]定义嵌套文档时,子文档不会自动继承顶层Schema的timestamps配置,仅主评论会生成createdAt和updatedAt字段。

以下是两种可行的解决方案:

方案一:补全子文档的timestamps配置

先定义顶层Schema,再为replies字段的子Schema显式添加时间戳配置:

const commentSchema = new Schema({
  body: {
    type: String,
    required: true
  },
  likes: {
    type: Number,
    default: 0,
  },
  wroteBy: {
    type: Schema.Types.ObjectId,
    ref: 'User'
  },
  replies: [] // 先初始化空数组
}, { timestamps: true })

// 为replies的子Schema开启timestamps
commentSchema.path('replies').schema.add({ timestamps: true })

方案二:复用Schema实例确保配置统一

先定义基础评论Schema,再将replies字段指向该Schema的数组类型,递归实现嵌套结构:

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

// 递归设置replies字段为当前Schema的数组
baseCommentSchema.path('replies', [baseCommentSchema])

const Comment = mongoose.model('Comment', baseCommentSchema)

验证方式:创建主评论并添加子评论后,查询文档即可看到所有层级的评论都包含createdAt和updatedAt字段。

内容的提问来源于stack exchange,提问作者STARCHILD

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 20:58:17