1

I am learning Node.js and having trouble displaying user name with return json. Here's what I'm using:

app.js

const express = require('express');
const path = require('path');
const expressHbs  = require('express-handlebars');
const methodOverride  = require('method-override');
const bodyParser = require('body-parser');
const flash = require('connect-flash');
const moment = require('moment');
const session = require('express-session');
const passport = require('passport');

// global variables
    app.use(function(req, res, next) {
    res.locals.success_msg = req.flash('success_msg');
    res.locals.error_msg = req.flash('error_msg');
    res.locals.error = req.flash('error');
    // res.locals.user = **req.user** || null;
    res.locals.user = **JSON.stringify(req.user)** || null;
    next();
});

list.hbs

On this page I dump the user object like so: {{user}}.

Tried JSON.stringify(req.user) and got the following output.

{"_id":"5a720ab7b09fed40ef0e0c96","uid":"3456","fname":"Brad","lname":"Jones","active":true,"accessLevel":3,"date":"2018-02-01T23:51:59.381Z"}

Tried req.user and got the following output.

{ _id: 5a720ab7b09fed40ef0e0c96, uid: '3456', fname: 'Brad', lname: 'Jones', active: true, accessLevel: 3, date: 2018-02-02T00:05:44.253Z } 

I've try accessing the name like so but nothing works.

  • {{user.lname}}
  • {{user['lname']}}

This is interesting, in the list.hbs I'm able to output the fname via each.

{{#each user}}
    ({{fname}})
{{/each}}

Notice the '()' in the output below, it appears there are multiple user.fname.

() () () (Brad) ()

Why might this be?

Update

Just tried this:

{{#each user}}
    ({{@index}} {{fname}})
{{/each}}

output this:
(0 ) (1 ) (2 ) (3 Brad) (4 )

Is there way to target the fourth value?

4
  • Did you simply try {{lname}} ? Commented Feb 2, 2018 at 6:36
  • Hi Gibin, thanks for your suggestion. Sadly it didn't work. Commented Feb 2, 2018 at 16:59
  • How about req.user.lname? May be I'm suggesting a blunder but just curious. Commented Feb 2, 2018 at 17:28
  • Tried {{req.user.fname}} too, no luck. The funny thing is a have a working identical site using ejs. I just prefer handlebars. Commented Feb 2, 2018 at 18:32

1 Answer 1

1

I found the problem, the model didn't not match the database columns.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.