Goran Goran - 3 months ago 13
Node.js Question

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

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

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
// define the schema for our user session model
var UserSessionSchema = new Schema({
sessionActivity: { type: Date, expires: '15s' }, // Expire after 15 s
user_token: { type: String, required: true }
});
module.exports = mongoose.model('UserSession', UserSessionSchema);


And I create a "session" in my app with:

...
var session = new Session();
session.user_token = profile.token;
session.save(function(save_err) {
if (save_err) {
....
} else {
// store session id in profile
profile.session_key = session._id;
profile.save(function(save_err, profile) {
if (save_err) {
...
} else {
res.json({ status: 'OK', session_id: profile.session_id });
}
});
...


The problem is that the document lives permanetly, its never expires. It should only live for 15 seconds (up to a minute). Whats wrong with my code? I have tried to set the expries: string to a number i.e 15, to a string '15s' and so on.

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