2

I use express-session package to handle sessions in express. I store sessions in mongodb using mongoose and connect-mongo for express-session store.

I am trying to delete some items from my collection when session that was created by express-session expires. Normally if I created this model myself, I would use something like:

// Init schema
const schema = new Schema({<schema fields>});

// Add .pre hook
schema.pre('remove', function pre(cb) {
    this.model('<Some items linked to this model>').remove({ <some association field>: this._id }, cb);
});

// Create model from schema
export const Model = model('ModelName', schema);

So now when record deleted (and I assume when it expires) I could also delete all linked items.

Problem is I don't know how to access schema/model that is created by express-session or connect-mongo to add hooks to this "Session" schema/model.

It's currently my first project using mongoose and express-sessions for sessions so I'm not quite sure how session model is created and provided to mongodb in the first place, but after mongo connection is established, I can see "sessions" collection in the database (cloud.mongodb.com), so I assume that at some point "Session" model is created by express-session or connect-mongo, but I can't find how to access it to add some hooks to it.

It's also weird is that if I try to see all defined models in mongoose long after initialisation (and after first session creation) like this: console.log(mongoose.models); I can only see models that are defined by me, but no "Session" model is displayed.

Edit: I can solve this by creating some job that deletes all records without existing links by iterating over every item, but I don't think it's very optimal way considering there are hooks available in mongoose.

  • I haven’t tried adding hooks to the schema but I think I have accessed it in the project. You could try adding hooked to it https://github.com/DashBarkHuss/setUserOnSession/blob/master/seed/addUserToSession.js – Dashiell Rose Bark-Huss Dec 03 '20 at 07:36

0 Answers0