sadrzadehsina
sadrzadehsina

Reputation: 1349

Mongoose add expires attribute for a specific field

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

Upvotes: 2

Views: 1671

Answers (1)

satish chennupati
satish chennupati

Reputation: 2650

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

Upvotes: 1

Related Questions