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

后端 未结 2 779
北恋
北恋 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()).

提交回复
热议问题