B
B
BarneyGumble2017-10-27 11:35:14
Mongoose
BarneyGumble, 2017-10-27 11:35:14

How to pass data received through Mongoose to the template?

Good afternoon. If I get data from the database and display it on the page like this, then everything is output normally:

var selectedUser = User.findOne({'_id': '5991bf82b9a87a624407907e'}, (err, user) => {
    console.log('result', err, user);
    res.render("userpage.hbs", {
        username: user.username 
    });
});

But what if I need to move the data outside the return function? Because this code no longer works, and I need to display the data exactly like this:
var selectedUser = User.findOne({'_id': '5991bf82b9a87a624407907e'}, (err, user) => {
    console.log('result', err, user);
});

res.render("userpage.hbs", {
    username: user.username
});

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
Egor Zhivagin, 2017-10-27
@BarneyGumble

var selectedUser = User.findOne({'_id': '5991bf82b9a87a624407907e'}, (err, user) => {
    console.log('result', err, user);
    someFunction(user);
});

function someFunction (user) {
    res.render("userpage.hbs", {
        username: user.username
    });
}

V
Vlad Shevchenko, 2017-10-27
@Stashevich

The 'user' variable is in a different scope, so the second option will not work in this form.
The easiest fix is ​​to create a variable that is global to these two function calls and write everything you need into it. And then read the value in the render function

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question