I have created a JavaScript class that attaches certain hooks to any mongoose schema, and creates log data in the database about that certain schema (when a schema is created what was saved, when it is updated the before and after snapshot of data, and also which user made that change/save)
let hooks = {
preSave : false,
preDeleteMany : false,
postInsertMany : false,
postDeleteMany : false
}
new GenericHook(UserSchema, 'User', hooks).init();
/**
* @typedef User
*/
module.exports = mongoose.model('User', UserSchema);
This is how certain hooks get attached to a schema, one of the methods from the class looks like this:
// POST: Triggers when Model.findOneAndDelete() method is called
createPostFindAndDeleteHook(){
let that = this;
this.genericSchema.post('findOneAndDelete', async function(document){
let currentUserId = localStorage.getItem('userId');
let options = {
model : that.schemaName,
action : actions.DELETE,
user : currentUserId ? currentUserId : null,
before_data : document,
after_data : null
}
await log.create(options);
});
}
The hooks are attached and they work perfectly fine, save the right data in before/after fields but the problem is that right now using the node-localstorage package, the last user to log in overrides userId item in local storage thus saving the wrong userId in the database.The item is set when a user logs in successfully.
localStorage.setItem('userId' , userData[0]._id);
Is there a way i can store the user id for each user and access it on the hook so i can save the right user creating/updating/deleting something from the database ?