01 Project – Node.js / Express / MongoDB – Part 12 – Building the home controller

At this point, our home.js file looks like below:

module.exports = {
  index: function(req, res) {
    res.render('index');
  }
};

Now, we will create a view model using sample data so we can see how it works.
So, the home.js file will look like is shown below:

var viewModel = {
  images: [
    {
      uniqueId: 1,
      title: 'Sample Image 1',
      description: '',
      filename: 'sample1.jpg',
      views: 0,
      likes: 0,
      timestamp: Date.now
    }, {
      uniqueId: 2,
      title: 'Sample Image 2',
      description: '',
      filename: 'sample2.jpg',
      views: 0,
      likes: 0,
      timestamp: Date.now
    }, {
      uniqueId: 3,
      title: 'Sample Image 3',
      description: '',
      filename: 'sample3.jpg',
      views: 0,
      likes: 0,
      timestamp: Date.now
    }, {
      uniqueId: 4,
      title: 'Sample Image 4',
      description: '',
      filename: 'sample4.jpg',
      views: 0,
      likes: 0,
      timestamp: Date.now
    }
  ]
};

module.exports = {
  index: function(req, res) {
    res.render('index', viewModel);
  }
};

If you take a look at the code then you can see that it is just a collection of objects. The variable we declared at the beginning of the code is named viewModel which is an object that has a single property called images. This property is an array with four sample images. These images have seven basic properties ( uniqueId , title , description , filename , views count, likes count, and timestamp).

The viewModel is pass to the res.render call.
Let’s start the server by running the command node index in the terminal then visit http://localhost:3300. Now you can see the images, although they are still broken since we didn’t upload any image yet.

Leave a Reply