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