Search code examples
node.jsexpressmongoosehandlebars.jspassport.js

How can i print only current user in HBS template


I want to print the currently logged in user, by getting the username from my database.

In my model, the username property holds the following schema:

{
  type: String, 
  required: true
}

index.js:

const users = require('../model/db');
router.get('/profiles/instructor', function (req, res, next) {
  users.find({}, 'username', (err, doc)=>{

    if(err){
      console.log('err while finding on instructor at index.js => ' + err)
    }else{
      console.log(doc)
      res.render('./profiles/instructor', { 
        title: 'Courstak | Instructor Profile',
        name: doc
// etc......
})

ex.hbs:

<h5>{{name}}</h5>

The issue that I am having is when I open my website, it shows all of the users within the database, not just the currently logged in user:

Screenshot of error:

enter image description here


Solution

  • You mentioned in the comments of your OP that you're using the passport-local strategy, and it would appear that it very nicely connects up with express in the way you would expect, so req.user should have the information you are looking for, which would make your code like so (assuming you're following the documentation to properly use passport-local):

    router.get('/profiles/instructor', function (req, res, next) {
        res.render('./profiles/instructor', { 
            title: 'Courstak | Instructor Profile',
            name: req.user.username
        });
    });
    

    What I would recommend also is using some middleware such as connect-ensure-login to ensure that the user is logged in and has a valid session. You can add the middleware above like so:

    var connectEnsureLogin = require('connect-ensure-login')
    
    router.get('/profiles/instructor',connectEnsureLogin.ensureLoggedIn(), function (req, res, next) {
        // ...
    }