Time to live in mongodb, mongoose dont work. Documents doesnt get deleted

后端 未结 2 780
北恋
北恋 2021-01-14 16:19

Im using this scheme for a session in my node.js app

var mongoose     = require(\'mongoose\');
var Schema       = mongoose.Schema;
// define the schema for o         


        
相关标签:
2条回答
  • 2021-01-14 16:30
    var UserSessionSchema   = new Schema({
        sessionActivity:    { type: Date, expires: '15s', default: Date.now }, // Expire after 15 s
        user_token:         { type: String, required: true }
    });
    

    A TTL index deletes a document 'x' seconds after its value (which should be a Date or an array of Dates) has passed. The TTL is checked every minute, so it may live a little longer than your given 15 seconds.

    To give the date a default value, you can use the default option in Mongoose. It accepts a function. In this case, Date() returns the current timestamp. This will set the date to the current time once.

    You could also go this route:

    UserSessionSchema.pre("save", function(next) { 
        this.sessionActivity = new Date(); 
        next(); 
    });
    

    This will update the value every time you call .save() (but not .update()).

    0 讨论(0)
  • To double check the indexes that have been created in the DB you can run this command in your mongo shell db.yourdb.getIndexes(). When changing the indexes you have to manually delete it in the collection before the new one will take effect. Check here for more information Mongoose expires property not working properly

    0 讨论(0)
提交回复
热议问题