01 Project – Node.js / Express / MongoDB – Part 13 – Creating the controller and the view model for the image page

The controller for the image will handle uploading and saving of the image files via the form on the homepage.

In the image controller we are going to build a view model for a single image. It will render a detailed view of an image (including the comments for the image).

Let’s go ahead and in the controllers/image.js file, let’s replace the index function code with the following code:

index: function(req, res) {
    var viewModel = {
      image: {
        uniqueId: 1,
        title: 'Sample Image 1',
        description: 'This is a sample image. How cool is that!',
        filename: 'sample1.jpg',
        views: 0,
        likes: 0,
        timestamp: Date.now()
      comments: [
          image_id: 1,
          email: 'test@testing.com',
          name: 'Noname Person',
          gravatar: 'http://lorempixel.com/75/75/animals/1',
          comment: 'This is just a comment for testing purpose ...',
          timestamp: Date.now()
          image_id: 1,
          email: 'test@testing.com',
          name: 'Noname Person',
          gravatar: 'http://lorempixel.com/75/75/animals/2',
          comment: 'This is a comment that follows the previous comment :)',
          timestamp: Date.now()
    res.render('image', viewModel);

The viewModel variable that we declared here contains the properties for the single image. Besides the image property, we have a comments property that contains an array of comment objects.

Let’s start the server by running the command node index and visit http://localhost:3300/images/1

Leave a Reply