使用节点保存到mongoDB时遇到问题

时间:2019-10-22 15:36:16

标签: node.js mongodb mongoose

我正在尝试从API响应中保存数据并保持获取空对象。我在代码中放置了console.log,它表明我从api得到响应。提取请求后,我似乎丢失了一些东西。

从index.js:

const express = require('express')
const bodyParser = require('body-parser')
const path = require('path')
const fetch = require('node-fetch')
const exphbs = require('express-handlebars')
const db = require('./src/models/movie')
require('./src/db/mongoose')
const Movie = require('./src/models/movie')

const app = express()
const port = process.env.PORT || 3000

// APP CONFIG
app.use(express.json())
app.use(bodyParser.urlencoded({extended: true}))

// ROUTES - ADD
app.post('/movies/:imdbID', (req, res) => {
    const imdb = req.params.imdbID
    const url = `**api link and key**${imdb}`

    const movie = fetch(url).then((res) => {
        return res.json()
    }).then((response) => {
        console.log(response)
        const addMovie = new Movie(response)
        db.Movie.create(addMovie, (err, newMovie) => {
            if(err){
                res.render('movie404')
            } else {
                res.redirect('/')
            }
        })
    }).catch((e) => {
        res.status(500).send(e)
    }) 
})

来自mongoose.js:

const mongoose = require('mongoose')

mongoose.connect('mongodb://127.0.0.1:27017/movietime-api', {
    useNewUrlParser: true,
    useCreateIndex: true,
    useUnifiedTopology: true,
    useFindAndModify: false
})

在details.handlebars中:

<h2>{{details.Title}}</h2>
<img src="{{details.Poster}}" alt="{{details.Title}}">
<p><em>{{details.Plot}}</em></p>
<p>Starring: {{details.Actors}}</p>
<p>Director: {{details.Director}}</p>
<form action="/movies/{{details.imdbID}}" method="POST">
    <button type="submit">Add</button>
</form>

来自movie.js:

const mongoose = require(“ mongoose”);

// MONGOOSE/MODEL CONFIG
const Movie = mongoose.model('Movie',{
    imdbID: String,
    Title: String,
    Poster: String,
    Director: String,
    Year: String,
    Plot: String,
    Ratings: String,
    Rated: String,
    Genre: String,
    Writer: String,
    Actors: String
});

module.exports = Movie;

我希望使用上述模型重定向到索引页,然后重定向到新的数据库条目。

1 个答案:

答案 0 :(得分:2)

您几乎已经需要照顾的事情很少了:

<div class="col-md-2">
     <select id="mySelect" >
     </select>
</div>

ref