【问题标题】:Set field after expire (MongoDB)过期后设置字段(MongoDB)
【发布时间】:2019-12-19 17:42:44
【问题描述】:

我会有一个小的数据库结构:

export const ApplicationSchema = new Schema({
  ownerId: String,
  ownerName: String,
  region: String,
  fromAddress: String,
  phone: String,
  cameAddress: String,
  status: {
    type: String,
    enum: ['new', 'booked', 'completed'],
    default: 'new'
  },
})

我需要更改“状态”,24 小时后状态应该等于“已预订”,该怎么做?

【问题讨论】:

    标签: javascript arrays mongodb mongoose time


    【解决方案1】:

    MongoDB 有一个名为 schedule triggers 的工具,它可以让你这样做: https://docs.mongodb.com/stitch/triggers/scheduled-triggers/

    但是,对于您的问题,这将是一个复杂而繁重的解决方案。您可以使用“createdAt”字段并为您的当前状态创建一个虚拟字段:

    export const ApplicationSchema = new Schema({
      ownerId: String,
      ownerName: String,
      region: String,
      fromAddress: String,
      phone: String,
      cameAddress: String,
      createdAt: Date,
      status: {
        type: String,
        enum: ['new', 'booked', 'completed'],
        default: 'new'
      },
      toJSON: { virtuals: true }
    })
    
    ApplicationSchema.virtual('status.current')
      .get(function () {
        // subtracting and checking if it's been a day in milliseconds
        if ((Date.now() - +new Date(this.createdAt)) >= 86400000) {
          return 'completed'
        }
    
        return this.status
      })
    

    您必须使用 status.current 而不是 status 来检查您的状态。 点击此处 (https://mongoosejs.com/docs/2.7.x/docs/virtuals.html) 了解有关虚拟字段的更多信息。

    【讨论】:

      【解决方案2】:

      我认为你不能单独使用 MongoDB 来做到这一点。
      在我的项目中,我使用了这个 npm 包:
      https://www.npmjs.com/package/cron

      这使您可以定期运行任务。类似于 Linux 系统上的 Cron 作业,但此包不依赖于 Linux Cron。

      【讨论】:

        猜你喜欢
        • 2014-11-08
        • 2012-09-05
        • 1970-01-01
        • 1970-01-01
        • 2014-02-21
        • 1970-01-01
        • 1970-01-01
        • 2016-09-14
        • 2022-08-14
        相关资源
        最近更新 更多