Full-Stack Web Development with Vue.js and Node

(singke) #1
Building the Real Application Chapter 5

});

const Movie = mongoose.model('Movie', MovieSchema)
module.exports = Movie;

Here, we have created a Movie model that would take all the four attributes that we have


added to our AddMovie.vue form earlier.


Adding movies controller


Now, the last thing we need to set up is an endpoint to save the movie to the database. Let's


create a folder called controllers in the root directory and add a file called movies.js


inside the directory and add the following code:


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

module.exports.controller = (app) => {
// 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);
});
});
};

Here we have added an endpoint that takes the post requests with the given params and


creates a Mongoose document in the database that we have configured.

Free download pdf