Mongoose add expires attribute for a specific field

浪尽此生 提交于 2021-01-28 19:05:46

问题


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;

})();

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!
  }
});

回答1:


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.

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).



来源:https://stackoverflow.com/questions/40867987/mongoose-add-expires-attribute-for-a-specific-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!