【问题标题】:set an expiration time for document node.js mongodb为文档node.js mongodb设置过期时间
【发布时间】:2021-06-07 21:31:27
【问题描述】:

所以我知道 mongo 中有一个叫做 TTL 的东西,但我认为它不适用于我想做的事情,我想从我的模式中设置一个文档,其中默认值为基本但当客户支付他的会员资格时我想将其设置为“加号”,我在控制器中进行了该查询,但我想知道当值为“加号”时是否有办法制作此文档以具有到期时间,例如 1 周或 1 个月,当时间结束时,将其再次设置为基本,有架构

const UserSchema = new Schema({
  username: {type: String, required: true},
  nombre_empresa: {type: String},
  email: {type: String, required: true, unique: true},
  password: {type: String, required: true},
  tipo_cuenta: {type: String, required: true},
  isNewUser: {type: String, default: 'basic'}
},
{
    timestamps: true
},
{ 
    typeKey: '$type' 
});

这里是我改变他状态的过程

userCtrl.renderMembershipSucess = async (req, res) => {
  const status = 'plus'
  const status_basic = 'basico'
  const status_user = await User.findByIdAndUpdate(
    req.user.id, {
      $set: { isNewUser: status }
    }
  )

  console.log(status_user)
  res.render('users/sucess')
}

【问题讨论】:

    标签: node.js mongodb mongoose mongodb-query


    【解决方案1】:

    与其依赖必须触发并正确更新用户记录的触发器,不如存储过期时间并在确定用户是否为加号时检查它。

    例如,您可以将 plusExpires 字段添加到默认值为 null 的用户架构中。当您将用户升级到 plus 时,请将 plusExpires 设置为不再有效的日期。

    将实例方法添加到架构以执行该检查:

    UserSchema.methods.isPlus = function() {
       return this.isNewUser == "plus" && (( this.plusExpires == null ) || (this.plusExpires > new Date())
    }
    

    那么任何时候你需要测试一个用户是否是加号,只需在用户对象上调用User.isPlus()

    【讨论】:

    • 感谢您的示例,我会尝试这样做
    【解决方案2】:

    我不认为 mongodb 提供了一种内置的方式来做你想做的事,但是你可以在每个午夜运行一个 cronjob 来获取你的“加号”客户,检查他们的会员资格并在必要时进行更新。

    另一种方式可能是设计您的 mongodb 集合以利用 TTL,您可以将 User 和 PlusMembership 集合分开,当用户付款时,插入带有 TTL 的 PlusMembership 数据

    【讨论】:

      猜你喜欢
      • 2022-07-09
      • 1970-01-01
      • 2019-07-26
      • 2014-06-13
      • 2013-01-02
      • 2017-08-22
      • 1970-01-01
      • 2011-06-21
      相关资源
      最近更新 更多