简体   繁体   中英

ExpressJs: Can't access object property from handlebars template

My Routes:

router.use(function(req, res, next) {
  res.locals.currentUser = req.user;
  next();
});

/* GET home page. */
router.get('/', function(req, res, next) {
  console.log(res.locals.currentUser.username); ==>> this is getting printed in console.
    res.render('index');
});

My index.handelbars

{{currentUser}} ===> this is getting displayed
{{currentUser.username}} ===> this is not

My User Schema

const UserSchema =
    new Schema({
        fullName: String,
        username: { type: String, required: true },
        password: { type: String, required: true },
        isMember: { type: Boolean, default: false },
        isAdmin: { type: Boolean, default: false }
    });

I am trying to access one of 'currentUser' object's property. Although the object itself gets displayed in the template but its property doesn't.

Change this

res.locals.currentUser = req.user;

to

res.locals.currentUser = req.user.lean(); // add lean()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM