Full-Stack Web Development with Vue.js and Node

(singke) #1
Building the Real Application Chapter 5

API endpoint to fetch all movies


First, we need to add an endpoint to fetch all the movies from the Mongo database. So, let's


first add an endpoint to fetch all the movies in controllers/movies.js:


const MovieSchema = require('../models/Movie.js');

module.exports.controller = (app) => {
// fetch all movies
app.get('/movies', (req, res) => {
MovieSchema.find({}, 'name description release_year genre', (error,
movies) => {
if (error) { console.log(error); }
res.send({
movies,
});
});
});

// add a new movie
app.post('/movies', (req, res) => {
const newMovie = new MovieSchema({
name: req.body.name,
description: req.body.description,
release_year: req.body.release_year,
genre: req.body.genre,
});

newMovie.save((error, movie) => {
if (error) { console.log(error); }
res.send(movie);
});
});
};

Now, if you hit the URL http://localhost:8081/movies, we should be able to see the


entire movie list that we have added via UI or the mongo shell itself. Here is what I have:

Free download pdf