Mongoose expire data but keep in database

express, mongodb, mongoose, node.js

Solution

You should use concept of Schema Reference for this. Save your expired field in another table and join your main `user_table` and `expire_table`(wxample name)

var UserSchema = new Schema({
    name: String,
    email: String
});

//save date by-default
//expire in 1 min as in your example
var expireSchema = new Schema({
    createdAt: { type: Date, default: Date.now, expires: '1m'  },
    user_pk: { type: Schema.Types.ObjectId, ref: 'user_expire'}
});

var userTable = mongoose.model('user_expire', UserSchema);
var expireTable = mongoose.model('expireMe', expireSchema);

//Save new user
var newUser =  new userTable({
    name: 'my_name',
    email: 'my_email'
});

newUser.save(function(err, result) {
    console.log(result, 'saved')
    var newExpire =  new expireTable({
        user_pk:result._id
    });
    //use _id of new user and save it to expire table
    newExpire.save(function(err, result) {
        console.log('saved relation')
    })
})

Now to detect whether session has expired or not

1. on executing this code before data gets expired

expireTable.findOne()
.populate('user_pk')
.exec(function (err, result) {
    if (err) throw err;
    console.log(result)
    if(result == null) {
        console.log('session has expired, renew session')
    } else {
        console.log('session is active')
    }
});

//output - session is active

2. on executing this code after data gets expired

expireTable.findOne()
.populate('user_pk')
.exec(function (err, result) {
    if (err) throw err;
    console.log(result)
    if(result == null) {
        console.log('session has expired, renew session')
    } else {
        console.log('session is active')
    }
});

//output - session has expired, renew session

Problem

I currently have data saving and expiring to/from a database via a mongoose schema like so: ``` var UserSchema = new Schema({ createdAt: { type: Date, expires: '1m' }, name: String, email: String }); ``` The only problem is that the document that's saved to the database is completely removed from the database. How would I refactor the above so that the name/email address stay in the database but if the user attempts to login after their expiry date then they're greeted with a message saying 'session has expired, renew session'. (or something similar) I'm wanting to do it this way because then if the user logs in with an expired email address the server is still able to lookup the email address and spit out a "expired session" message rather than a "not found" error which is what happens when data is deleted. So to reiterate, how do I keep expired data in a mongo/mongoose database so the app is able to find the email address the user is attempting to login with but if their session has expired they need to renew the session?

Original source