Kunok Kunok - 8 months ago 34
Node.js Question

Express - refresh view variable when database contents change

I am using Express and I am generating pages from database. On server start I have navigation generation.

This block is executed on server start:

.then(() => {
.catch(err => {

I have this code that generates navigation:

generators.navigation = function(){
var db = require('./database.js').db;
var data = db.collection('navigation').find({},{_id:0,path:1,title:1});
var nav = []
data.on('data', doc => {
data.on('end', () => {
generators.navigation = nav;

Which is then used in page rendering:

for (let page of pages) {
if(req.params.path === page.path){
res.render(page.type, {

And in my view (using handlebars):

{{#if_eq page.contents.nav.type 'default'}}
{{#each navigation}}
<a class="item no-mobile" href="{{this.path}}">{{this.title}}</a>

The problem is that when new object is inserted in database, this doesn't update navigation, that happens because this code is only executed at server start, and it is required to restart server in order to read new changes in database.

Which is recommended way for it to watch for database updates and refresh navigation object when database is updated?

Answer Source

don't write generators.navigation(); on server start . There are hooks provided in nodejs that get fired before request /after request so you can use this hooks to call generators.navigation() function. As iam assuming there would be on function that will add nav items to database . So as soon as that request is completed you can call generators.navigation() in that requests after request hook