S
S
Senbonzakuraa2020-03-05 17:01:38
Node.js
Senbonzakuraa, 2020-03-05 17:01:38

How to pass session data to a view?

Do I understand correctly that when using a login with passport and creating an express session, I get the following session:

Session {
  cookie: { path: '/', _expires: null, originalMaxAge: null, httpOnly: true },
  flash: {},
  passport: { user: '5e5fd30277b47f2c6838e070' }
}

and in order to display the session data in the view, I need to make a middleware that will take the user id from the session and take the user model from mongo and then can I give the model data to the template? Only how to transfer it in such a way that I can use it in all views?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Cheremkhin, 2020-03-05
@Senbonzakuraa

Passed separately to each template, if necessary

router('/user', (req, res, next) =>{
 const {userId} = req.session; // здесь могу ошибаться посмотрите док password...
 User.findById(userId)  // model User в mongoose
   .then(user=>{
     const viewModel ={
       user,  //user для этой сессии
       ...      // что то еще нужное
     };
     res.render('view-user', viewModel)
  })
  .catch(err=>next(err);
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question