The like button and updating an image model

Next, let's add support for the Like button. Remember that our Like button works a little differently. It uses AJAX with jQuery so that data can be sent and received in real time without reloading the entire page. The experience for the user is seamless and enjoyable, as they don't lose their scroll place on the page or experience any other jarring UI-related issues.

The endpoint that the Like button hits is /images/:image_id/like, so we are going to use the value in the URL for image_id to find and retrieve the image in MongoDB, increment its likes value by 1, and then return the new total number of likes for the image (so that the UI can update with the new value).

Currently, the like function in controllers/image.js only does a simple JSON response with a hardcoded value of 1:

res.json({likes: 1}); 

Let's replace that original code with new code that will use the Mongoose Image model to find an image with a filename that matches the image_id passed in via the URL:

Models.Image.findOne({
filename: { $regex: req.params.image_id }
},
(err, image) => {
if (!err && image) {
image.likes = image.likes + 1;
image.save((err) => {
if (err) {
res.json(err);
} else {
res.json({ likes: image.likes });
}
});
}
});

Assuming the callback function receives a valid image model response from the query, we'll then increment its likes property, and since the model is then modified, we need to execute its save function. Inside the save function's callback, we send a JSON response with the real current value of the image's likes back to the browser.

Sometimes, we will use shorthand in JavaScript and write something similar to the following:
if (!err && image)
In the if statement in the preceding example, we are saying, if the err object is false (that is null) and the image object is true (that is not null), then we're good to go!

With this code in place, you can run the app again and test out the Like button by viewing the image that you uploaded earlier and simply clicking on Like. If it worked, the counter next to the button should increase by one. Refresh the page, and the likes count should remain as the new value.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.190.239.166