Search code examples
node.jstemplate-enginenunjucks

can't pass object to html with nunjucks


I want to use Nunjucks to pass data from a mongoDB server to my html file to render on load.

App.js

app.get('/', function(req, res) {
    database.retrieveComments(req, function(err,result) {
        console.log(result);
        res.render('index.html', result);
    });
});

where my database connection file has this:

connection.js

retrieveComments: function(req, callback) {
    db.collection('comments').find().toArray(function(err,result) {
        if (result.length > 0) {
            return callback(null, result);
        };
    });             
},

Lastly, in my HTML file I have this part:

index.html

<div id="p" class="task" commentId = "1">
    1st comment {{ result }}
</div>

I can see result when I console.log it out, but I don't seem to render it in the html file when I browse to the localserver. If I just pass a string, I can see it, but not when I pass the result object.

I'm wondering if there's some asynchronous node black magic working here, or whether I'm missing some key Nunjucks element.


Solution

  • app.get('/', function(req, res) {
        database.retrieveComments(req,function(err, result) {
            if (err)
                return next(err); // Always check error
            console.log('DB result: ', result); // Verify that result is not empty
            res.render('index.html', {result: result});
        });
    });
    

    retrieveComments : function (req, callback) {
        db.collection('comments').find().toArray(function(err, result) {
            // callback must be called always
            if (err)
                return callback(err);
    
            if (result.length == 0) 
                return callback(new Error('Result is empty!')); 
    
            callback(null, result);
        });
    }, 
    

    <div id="p" class="task" commentId = "1">
    1st comment {{ result }}
    {{ result[0].name }} {# result is Array, right? #}
    </div>