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

Mongoose中如何记录published属性切换对应的publishedAt与unpublishedAt时间戳

实现方案

方法1:添加pre('save')中间件(适配save()方法调用场景)

在你现有Schema定义完成后、导出模型前插入如下中间件,即可在保存文档时自动识别published字段的状态切换,对应写入时间:

offerSchema.pre('save', function(next) {
  // 处理新建文档的初始状态
  if (this.isNew) {
    if (this.published) {
      this.publishedAt = new Date();
    }
    return next();
  }
  // 判断published字段是否发生变更
  if (this.isModified('published')) {
    // 从false切换为true,记录发布时间
    if (this.published === true) {
      this.publishedAt = new Date();
    }
    // 从true切换为false,记录下架时间
    if (this.published === false) {
      this.unpublishedAt = new Date();
    }
  }
  next();
});

方法2:补充查询更新钩子(适配findByIdAndUpdate/updateOne等直接更新场景)

如果业务中会使用Mongoose的查询更新方法而非手动调用save(),需要额外添加对应中间件才能触发时间写入逻辑:

offerSchema.pre('findOneAndUpdate', function(next) {
  const update = this.getUpdate();
  // 兼容直接传更新字段和用$set操作符两种写法
  const newPublished = update.$set?.published ?? update.published;
  if (newPublished === undefined) return next();
  if (newPublished === true) {
    this.set({ publishedAt: new Date() });
  }
  if (newPublished === false) {
    this.set({ unpublishedAt: new Date() });
  }
  next();
});

可选调整

如果需要留存每次状态切换的历史记录而非仅保留最后一次切换时间,可把Schema里的publishedAt/unpublishedAt改成数组类型,每次状态切换时向数组push新的时间戳即可。

内容的提问来源于stack exchange,提问作者Kenan Bajrić

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 02:54:02