使用nodejs和ejs将数据保存到mongodb

时间:2018-11-14 18:11:28

标签: javascript node.js mongodb ejs

app.js

const mongoose = require('mongoose');
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const methodOverride = require('method-override');
app.use(bodyParser.urlencoded({extended: true}));
app.use(methodOverride('_method'));
const request = require('request');
app.set('view engine', 'ejs');

mongoose.connect('mongodb://localhost/movies_project')
.then(() => { console.log('Connected to mongodb')})
.catch( err => console.error('Could not connect', err));

let movieSchema = new mongoose.Schema({
title: String,
poster: String,
year: Number,
genre: String,
plot: String,
director: String,
actors: String,
ratings: Number,
votes: Number,
runtime: String,
    imdbID: String
})

const Movie = mongoose.model('Movie', movieSchema);    

app.get('/', (req, res) => {
Movie.find({}, (err, movies) => {
    if(err) console.log(err)
    else res.render('landing', {movies: movies})
 })

 })

 app.get('/movies',(req, res)=>{

 let query = req.query.search || 'Spider Man';
 let url = 'http://www.omdbapi.com/?apikey=2edb4869&t=' + query
 request(url, (error, response, body) =>{
    if(!error && response.statusCode == 200){
        let data = JSON.parse(body)
        res.render('results',{data: data })
        }
})
});

app.post('/movies',(req, res) => {
let title = req.body.title;
let poster = req.body.poster;
let genre = req.body.genre;
let plot = req.body.plot;
let director = req.body.director;
let writer = req.body.writer;
let actors = req.body.actors;
let imdbRatings = req.body.ratings;
let imdbVotes = req.body.votes;
let runtime = req.body.runtime;    

let newMovie = { title: title, poster: poster, genre: genre, plot: plot, 
director: director,
     writer: writer, actors: actors, ratings: imdbRatings, votes: imdbVotes, 
runtime: runtime}

Movie.create(newMovie, (err, createdMovie) =>{
    if(err) console.log(err)
    else res.redirect('/')
})
})

app.get('/movies/new', (req, res) =>{
res.render('new')
})


app.get('/movies/:id/edit', (req, res) => {
Movie.findById(req.params.id, (err, foundMovie)=>{
    if(err) res.redirect('.')
        else res.render('edit', {
            movie: foundMovie
        })
})

})

app.put('/movies/:id', (req, res) =>{

Movie.findByIdAndUpdate(req.params.id, req.body.movie, (err, updatedMovie) 
  =>{
    if (err) console.log(err)
        else res.redirect('/')
})
})

app.delete('/movies/:id', (req, res) =>{
Movie.findByIdAndRemove(req.params.id, (err) =>{
    if(err) console.log(err)
        else res.redirect('/')
})
})

const port = process.env.PORT || 3000;
app.listen(port, () => console.log(`Listening on port ${port}`));

results.ejs

<% include partials/header %>


<div class="container">
<h1>Search for a movie</h1>

<form action="/movies" method="GET">
    <input type="text" placeholder="Search for a movie" name="search">
    <input type="submit">
</form>
</div>
<hr>

<form action='/movies' method="POST">
<div class="table-responsive">

    <table class="table table-hover">
        <thead>
            <tr>
                <th>Poster</th>
                <th>Movie</th>
                <th>Genre</th>
                <th>Plot</th>
                <th>Director</th>
                <th>Writer</th>
                <th>Actors</th>
                <th>Rating</th>
                <th>Votes</th>
                <th>Runtime</th>
                <th>Action</th>

            </tr>
        </thead>
        <tbody>

            <tr>

                <td name="poster"><img src="<%= data['Poster']%>" 
width="50px" height="50px"></td>
                <td name="Title">
                    <%= data["Title"] %>
                </td>
                <td name="genre">
                    <%= data["Genre"] %>
                </td>
                <td name="plot">
                    <%= data["Plot"] %>
                </td>
                <td name="director">
                    <%= data["Director"] %>
                </td>
                <td name="writer">
                    <%= data["Writer"] %>
                </td>
                <td name="actors">
                    <%= data["Actors"] %>
                </td>
                <td name="imdbRating">
                    <%= data["imdbRating"] %>
                </td>
                <td name="imdbVotes">
                    <%= data["imdbVotes"] %>
                </td>
                <td name="runtime">
                    <%= data["Runtime"] %>
                </td>


                <td>

                    <button class="btn btn-lg btn-primary center-block" 
 submit>Add movie</button>



                </td>

            </tr>

        </tbody>
    </table>

</div>

 </form>

<% include partials/footer %>

我从OMDB API中获取数据,当我单击表格下方的按钮时,需要将其保存到数据库中。其他一切正常,我可以使用表单将电影保存到数据库,但是一旦我从API得到响应,就无法弄清楚该怎么做,因此我不必手动键入所有内容。

0 个答案:

没有答案