I am using express-session and mongoose. When the user authenticates, I put his data in the session:
req.session.user = candidate
req.session.isAuthenticated = true
req.session.save()
I've created middleware for checking if req.session.user exists and putting it in the request:
if (!req.session.user) {
return next()
}
req.user = await User.findById(req.session.user._id)
next()
If I use instead of req.user = await User.findById(req.session.user._id) just this: req.user = req.session.user It will not allow me to access userSchema methods as if in that case req.user isn't a Schema Type Object.
Can you please explain, how and why it works like this? Thanks in advance:)
The express-session
package documentation mentions this:
To store or access session data, simply use the request property req.session, which is (generally) serialized as JSON by the store.
So for the purpose of storage, the object referenced at req.session
is actually serialized - ie turned into a string representation - to the session store on save, and later deserialized from the session store when an request comes in.
As part of this serialization process, some information is lost - including object methods and maybe more importantly the actual type of the object. As a result, when the object is restored from the serialized version, what you're getting is basically a generic object with only non-function properties.
Note this process is recursive, so what applies to req.session
applies to any nested object.
You can simulate this with the JSON serializer that is part of the standard library:
class Session {
randomMethod() { }
}
var session = new Session()
session.someData = "Some data"
var serialized = JSON.stringify(session)
var restored = JSON.parse(serialized)
console.log(session instanceof Session) // true
console.log(restored instanceof Session) // false
console.log("randomMethod" in session) // true
console.log("randomMethod" in restored) // false
console.log(session.someData) // "Some data"
console.log(restored.someData) // "Some data"