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

如何在Node.js MongoDB原生驱动中自动添加createdAt/updatedAt时间戳

Node.js 原生MongoDB驱动自动添加时间戳实现方案

原生MongoDB Node.js驱动本身没有内置自动生成createdAt、updatedAt字段的能力,你可以通过以下两种常用方案实现需求:

方案1:业务层封装注入(兼容性最好,无版本限制)

直接在操作数据库的逻辑中手动添加时间字段,重复逻辑可以封装为公共工具函数:

  • 插入文档时,同时添加两个时间字段为当前时间:
// 插入单条文档示例
await collection.insertOne({
  title: "测试文档",
  content: "业务内容",
  createdAt: new Date(),
  updatedAt: new Date()
})
  • 更新文档时,仅修改updatedAt字段即可:
// 更新文档示例
await collection.updateOne(
  { _id: targetDocId },
  {
    $set: {
      title: "修改后的标题",
      updatedAt: new Date()
    }
  }
)

方案2:数据库层面配置自动生成(MongoDB 5.0+支持)

创建集合时配置JSON Schema规则,给时间字段设置默认值,插入文档时不需要手动传值,数据库会自动生成:

// 创建集合时配置Schema规则
await db.createCollection("posts", {
  validator: {
    $jsonSchema: {
      bsonType: "object",
      required: ["createdAt", "updatedAt"],
      properties: {
        createdAt: {
          bsonType: "date",
          default: new Date()
        },
        updatedAt: {
          bsonType: "date",
          default: new Date()
        }
      }
    }
  }
})

更新操作可以搭配$currentDate操作符,无需手动生成时间对象:

await collection.updateOne(
  { _id: targetDocId },
  {
    $set: { title: "修改后的标题" },
    $currentDate: { updatedAt: true }
  }
)

提示:该方案仅支持MongoDB 5.0及以上版本,低版本实例请使用方案1实现。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 13:54:04