'Display JSON data with Node.js and Handlebars

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?



Solution 1:[1]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 halfer