Search code examples
node.jsexpressmongoosehandlebars.js

How do I have a variable available to display on my success page, after adding items to a database via a /POST route?


I would like to display the doc.id variable of a successful /POST of data to a route, on the success page that the user will be redirected to afterward. I'm trying to work out how to carry the variable teamId through to the Handlebar template page success.hbs

I've tried making it a variable, and setting up a Handlebar helper to display it, but nothing is working.

/POST route redirecting to success.hbs:

app.post('/create', (req, res) => {
var players = [];
var playerObj = {};
for (let i = 1; i < 21; i++) {
    var playerObj = { playerName: req.body[`player${i}Name`], playerNumber: req.body[`player${i}Number`], playerPosition: req.body[`player${i}Position`] };
    if (req.body["player" + i + "Name"] === '') {
        console.log("Empty player name detected, disregarding");
    } else {
        players.push(playerObj);
    }
}

var newTeam = new Team({

    // WEB SETUP BELOW
    "team.teamRoster.teamCoach": req.body.coachName,
    "team.shortTeamName": req.body.teamShortName,
    "team.teamName": req.body.teamName,
    "team.teamRoster.players": players
});

newTeam.save().then((doc) => {
    var teamId = doc.id;
    console.log(teamId);
    res.render('success.hbs');
    console.log("Team Added");
}, (e) => {
    res.status(400).send(e);
});
});

/views/success.hbs

<div class="container-fluid" id="body">
    <div class="container" id="page-header">
        <h1><span id="headline">Team Added Succesfully</span></h1>
        <hr>
            <h3><span id="subheadline">Input the following address as a JSON Data Source within vMix.</span></h3>
            <span id="content">
                <div class="row">
                    <div class="container col-md-12">
                        {{{teamId}}}
                    </div>
                </div>
            </span>
        </div>
    <hr>
</div>

I'd like a Handlebar helper to get the doc.id value of the /POST request, and store it as teamId to display on the success page. It's finding nothing at the moment.

Any help is appreciated.


Solution

  • Node.js can pass variables to the handlebars-view like this:

    newTeam.save().then((doc) => {
        var teamId = doc.id;
        console.log(teamId);
        res.render('success.hbs', {
            teamId
        });
        console.log("Team Added");
    }, (e) => {
        res.status(400).send(e);
    });