I am creating a e-commerce website where I store all the data in database as well as session store. For logged-in users, only the login credentials are stored in the session store. So, whenever the website is run for the first time, the data should be fetched from database from the data we get from session store but if i use a middleware for this purpose, it is not efficient as the middleware runs on every request. So, is there any way to solve this problem or is there any better solution to this problem which is more efficient? And also, you may wonder why I don't store data in the session store directly. So, the problem is, when I fetch data from session store, it is not returned in the form of a mongoose model so I have to call the database once. I use mongo store, express, node and ejs.
This is the middleware I use in my index file to fetch data from database in the mongoose model using the id stored in my session store during login.
app.use(async (req, res, next) => {
try {
if(req.session.userid) {
req.user = await user.findById(userid)
}
} catch(err) {
res.redirect('/' + req.oldUrl + '?err=UserNotFound')
}
next()
})
app.use(session({
secret: 'secret',
saveUninitialized: false,
resave: false,
cookie: {
maxAge: 1000 * 60 * 60 * 24 * 365 * 100,
secure: false
},
store: store
}))
This is my mongoose model
const mongoose = require('mongoose')
const Schema = mongoose.Schema
const userschema = new Schema({
Name : {
type : String,
required : true
},
Email : {
type : String,
required : true
},
Password : {
type : String,
required : true
},
IsSeller : {
type : Boolean,
defualt : false
},
Shopname : {
Type : String,
default : "-"
},
Cart : {
Items : [
{
productId : {
type : Schema.Types.ObjectId,
ref : 'product',
required : true
},
quantity : {
type : Number,
required : true
}
}
]
},
Myproducts : {
items : [
{
productId : {
type : Schema.Types.ObjectId,
ref : 'product',
required : true
},
quantity : {
type : Number,
required : true
}
}
]
},
Sdate : {
type : String,
default : "-"
}
})
module.exports = mongoose.model('user', userschema)
You can use
express-sessions
directly in one of your controllers if you don't want to use it as a general middleware. If you set a session cookie when you log in and only check it next time the user logs in, make sure the user is logged out when tab or browser is closed, or after a certain time if you want to keep it more flexible and let users bypass the login form for x amount of time.