首页 > 解决方案 > 基于 JSON 文件创建 JSON 对象

问题描述

GET当我向omdbapi.com 发送请求时,我在检索有关电影的信息时遇到问题 。

这是处理POST对我的数据库的请求的代码:

const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
const XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;

const Movie = require('../models/movie');

router.post('/', (req, res, next) => {

    var temp;
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function(){
        if (this.readyState == 4 && this.status == 200) {
            temp = JSON.parse(this.responseText);
        }
    };
    xhr.open("GET", "http://www.omdbapi.com/?t=" + req.body.title + "&apikey=xyz", true);
    xhr.send();

    const movie = new Movie({
            _id: new mongoose.Types.ObjectId(),
            title: req.body.title,
            movieInfo: temp,
            comment: req.body.comment
    });

    movie
    .save()
    .then(result => {
        console.log(result);
        res.status(201).json({
            message: 'Created movie succesfully',
            createdMovie: {
                _id: movie._id,
                title: movie.title,
                movieInfo: movie.movieInfo,
                comment: movie.comment
            }
        });
    })
    .catch(err => {
        console.log(err);
        res.status(500).json({
            error : err
        });
    });
});

module.exports = router;

我的问题是,除了movieInfo之外的所有东西都通过了,我想成为一个嵌套的JSON对象,比如

createdMovie{
 ...
 movieInfo: {
  Title: a,
  Actors: b,
  ...
  ...
 }
 ...
}

这是我工作的猫鼬模式

const mongoose = require('mongoose');

const movieSchema = mongoose.Schema({
    _id: mongoose.Schema.Types.ObjectId,
    title: String,
    movieInfo: String,
    comment: String
});

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

当我POST看电影时,这就是我在测试时得到的(我使用 Postman 进行测试)。

{
    "message": "Created movie succesfully",
    "createdMovie": {
        "_id": "5b7b0da48f5fb04e3c0f740b",
        "title": "Goodfellas",
        "comment": "some comment"
    }
}

所以我错过了movieInfo,我不知道是因为它甚至没有到达对象,因为我以错误的方式传递它,或者它只是没有显示。尝试了不同的猫鼬类型,例如String, ArrayMixed但都没有奏效。

如果请求成功,您得到的 JSON 看起来像这样

{
    "Title":"Goodfellas",
    "Year":"1990",
    "Rated":"R",
    "Released":"21 Sep 1990",
    "Runtime":"146 min",
    "Genre":"Crime, Drama",
    "Director":"Martin Scorsese",
    "Writer":"Nicholas Pileggi (book), Nicholas Pileggi (screenplay), Martin Scorsese (screenplay)",
    "Actors":"Robert De Niro, Ray Liotta, Joe Pesci, Lorraine Bracco",
    "Plot":"The story of Henry Hill and his life in the mob, covering his relationship with his wife Karen Hill and his mob partners Jimmy Conway and Tommy DeVito in the Italian-American crime syndicate.","Language":"English, Italian","Country":"USA","Awards":"Won 1 Oscar. Another 43 wins & 37 nominations.",
    "Poster":"https://m.media-amazon.com/images/M/MV5BY2NkZjEzMDgtN2RjYy00YzM1LWI4ZmQtMjIwYjFjNmI3ZGEwXkEyXkFqcGdeQXVyNzkwMjQ5NzM@._V1_SX300.jpg",
    "Ratings":[{"Source":"Internet Movie Database","Value":"8.7/10"},{"Source":"Rotten Tomatoes","Value":"96%"},{"Source":"Metacritic","Value":"89/100"}],
    "Metascore":"89",
    "imdbRating":"8.7",
    "imdbVotes":"855,144",
    "imdbID":"tt0099685",
    "Type":"movie",
    "DVD":"26 Mar 1997",
    "BoxOffice":"N/A",
    "Production":"Warner Bros.",
    "Website":"N/A",
    "Response":"True"
}

我想把它放在下面movieInfo,整个事情。如何实现?

标签: javascriptjsonnode.jsmongodbmongoose

解决方案


将movieInfo 数据类型更改为对象。

const movieSchema = mongoose.Schema({
    _id: mongoose.Schema.Types.ObjectId,
    title: String,
    movieInfo: Object,
    comment: String
});

推荐阅读