Mongoose 为特定字段添加 expires 属性 [英] Mongoose add expires attribute for a specific field

查看:40
本文介绍了Mongoose 为特定字段添加 expires 属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为我的 Web 应用程序制作了一个基于令牌的身份验证系统,我需要为令牌字段设置一个到期日期.保存tokenuser模型如下:

I have made a token based authentication system for my web application and I need to have an expiration date for the token field. The user model which keeps token is as follow:

module.exports = (function() {

  var userSchema = new Schema({
    phone: String,
    token: {
      value: { type: String, lowercase: true, trim: true }
    },
    verificationCode: Number,
    createdAt: { type: Date, default: Date.now() }
  });

  var User = mongoose.model('User', userSchema);

  return User;

})();

我想知道有没有办法为 token 字段设置到期日期属性.其实我想在我的代码中有类似下面的东西来检查令牌是否过期:

I am wondering is there any way to have an expiration date attribute for the token field. Actually I want to have something like below in my code to check whether token is expired or not:

User.findOne({}, function( err, user ) {
  if (user.token.isExpired()) {
    // do something!
  }
});

推荐答案

感谢 @dyouberg 提出这个问题.是的@sadrzadehsina 您也可以使用 TTL 索引,但从您的需求角度来看,这里唯一的缺点是一旦文档通过 TTL mongodb 将从集合中删除该文档.如果您可以丢失文档,那么 TTL 可能是最好的选择,因为一切都将由 mongodb 自己处理.您需要做的就是在集合上创建一个索引.

thanks for bring this up @dyouberg. Yes @sadrzadehsina You can use TTL indexes also but the only drawback here from your requirements perspective is once a document passes the TTL mongodb will remove the document from the collection. if you are ok to loose the documents probably TTL is the best option since everything will be taken care by mongodb itself. All you need to do is create an index on the collection.

如果您打算保留文档,那么 TTL 可能没有帮助,但是您可以构建一个简单的逻辑(我在评论中有它).

if you your intention is to keep the documents then TTL may not be helpful however you can build a simple logic(i have it in the comment).

这篇关于Mongoose 为特定字段添加 expires 属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆