如何使用nodejs和mongoose获取多个JSON对象?

时间:2018-01-21 12:15:26

标签: json node.js mongodb

我希望获得season:2008season:2009的所有JSON对象。季节领域有2008,2009,2010,2011,2012,2013,2014,2015,2016值。

我希望通过API端点获取所有具有字段season:2008的JSON对象。请参阅下面的代码以获得更多说明,但它仅返回null

JSON回复:

{
  "_id": "5a63051735aaddd30d1d89cc",
  "id": 1,
  "season": 2008,
  "city": "Bangalore",
  "team1": "Kolkata Knight Riders",
  "team2": "Royal Challengers Bangalore",
  "toss_winner": "Royal Challengers Bangalore",
  "toss_decision": "field",
  "result": "normal",
  "dl_applied": 0,
  "winner": "Kolkata Knight Riders",
  "win_by_runs": 140,
  "win_by_wickets": 0,
  "player_of_match": "BB McCullum",
  "venue": "M Chinnaswamy Stadium",
  "umpire1": "Asad Rauf",
  "umpire2": "RE Koertzen",
  "umpire3": ""
}

代码:

/*      <---Uncomment
app.get('/api/matches/:match_id', (req, res) =>{

    let match = req.params.match_id;

    matches.findOne({id: parseInt(match)}).then(Match =>{

        res.json(Match);
    });

});
*/     <---Uncomment

app.get('/api/matches/:season', (req, res) =>{

    let Season = req.params.season;

    matches.find({season: parseInt(Season)}).then(eachOne =>{

        res.json(eachOne);
    });

});

在matches.js中:

const mongoose = require('mongoose');

let Schema = mongoose.Schema;

const matchSchema = new Schema({

    match_id:{
        type:Number,
        required:true
    },

    season:{
        type:Number,
        required:true
    },

    city:{
        type:String,
        required:true
    },

    date:{
        type:Number
    },

    team1:{
        type:String,
        required:true
    },

    team2:{
        type:String,
        required:true
    },


    toss_winner:{
        type:String,
        required:true
    },

    toss_decision:{
        type:String,
        required:true
    },

    dl_applied:{
        type:Number
    },

    winner:{
        type:String,
        required:true
    },

    win_by_runs:{
        type:Number,
        required:true
    },

    win_by_wickets:{
        type:Number,
        required:true
    },

    player_of_match:{
        type:String,
        required:true
    },

    venue:{
        type:String,
        required:true
    },

    umpire1:{
        type:String,
        required:true
    },

    umpire2:{
        type:String,
        required:true
    },

    umpire3:{
        type:String
    }

});

const matches = mongoose.model('matches', matchSchema);

module.exports = matches;

每当我转到网址http://localhost:5000/api/matches/2008http://localhost:5000/api/matches/2010时,都会null

2 个答案:

答案 0 :(得分:0)

在/ api / matches /:season之前的http://localhost:5000/api/matches/2010之前,应该有一个路由名称。让我们说你的路线名称是match.js你的网址看起来像http://localhost:5000/match/api/matches/2010。取决于你如何定义index.js

答案 1 :(得分:0)

现在你们两条路线都是相同的...你们必须为两个查询制作不同的路线...因为查询不知道什么是match_id和session ...如果你为路由保留相同的名称,那么查询哪个是在代码之前将首先执行

更改两条路线

    app.get('/api/match_id/:match_id)

    app.get(/api/matches/:season)