0

I have a nodejs application. I'm using handlebars js as a view engine. I'm trying to access one element from nested object that I'm passing to the hbs view.

router.get('/view_users/:id', function (req, res, next) {
Users.find({ userId: req.params.id }, function (err, users) {
    if (err) {
        throw err;
    } else {
        res.render('view_user', { title: 'Users', user: users});
    }
})

});

and then in the view_user I would like to access only one users.name.<p>{{users.name}}</p> (Without built-in helpers such as #each because it will return me a list of all users)

I tried {{user.name}}, {{name}}, and {{{user.name}}} but it returns me undefined.

Users is the mongoose Schema.

How can I do it? Thanks.

6
  • Does {{title}} work? Commented Jan 5, 2017 at 23:27
  • Yes it works fine Commented Jan 5, 2017 at 23:53
  • I believe the problem with the users object Commented Jan 5, 2017 at 23:54
  • Well it look like so yes. Can you do a console.log(JSON.stringify(users)); right before your call to the render method? Commented Jan 6, 2017 at 0:00
  • It prints the object[{"_id":"586abcad062b2b1254bb5303","name":"Test3423","description":"","departmen tName":"Test3","__v":0,"departmentId":["5864345ef7834d3fc07d8d6c"]}] Commented Jan 6, 2017 at 1:29

2 Answers 2

1

find() method will return a list of documents. That's why you get (from your comment above): object[{"_id":"586abcad062b2b1254bb5303","name":"Test3423","‌​description":"","dep‌​artmen tName":"Test3","__v":0,"departmentId":["5864345ef7834d3fc07d‌​8d6c"]}]. This is an array with you model inside.

Use instead findOne method, it will return directly the User document. You make your request using userId, so you will always get the good document.

You can read more from the docs: http://mongoosejs.com/docs/queries.html

Anywhere a callback is passed to a query in Mongoose, the callback follows the pattern callback(error, results). What results is depends on the operation: For findOne() it is a potentially-null single document, find() a list of documents, count() the number of documents, update() the number of documents affected, etc. The API docs for Models provide more detail on what is passed to the callbacks.

Another solution is to get the first element of the users array:

res.render('view_user', { title: 'Users', user: users[0] });

Hope it helps.

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

1 Comment

Thanks for your help.
0

Use findOne if you want to search for a particular user it will provide a user object. where find will return an array of users/user.

try this:

router.get('/view_users/:id', function(req, res, next) {
    Users.findOne({ userId: req.params.id }, function(err, user) {
        if (err) {
            throw err;
        } else {
            res.render('view_user', { title: 'Users', user: user });
        }
    })
})

Or

use the first element of the array if you have only one user (not recommended for multiple user sets).

res.render('view_user', { title: 'Users', user: users[0]});

Or

Iterate in view (recommended for multiple users list)

   {{#each this}}
        {{name}}
    {{/each}}

Here's a simplified fiddle to show what I'm asking: http://jsfiddle.net/KPCh4/2/

Happy Coding :)

2 Comments

Thanks for your help.
I wonder why you can't directly reference a property in an object with Handelbars. Users.findOne() returns a single user object, like {name: "John", email: "[email protected]"}. In the view, it seems you can only access it via the {{#each}} iterator, rather than directly with {{user.name}}.

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.