[英]How to get specific JSON data from REST API using Nodejs?
我想從所有匹配項中獲取特定的JSON數據,比如說match = 2數據。 我無法獲取存儲在MongoDB中的必需數據。
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": ""
}
我可以使用以下代碼獲得577個匹配項的所有JSON數據。
app.get('/api/matches', (req, res) =>{
matches.find({}).then(eachOne => {
res.json(eachOne);
});
});
但是現在我不想獲取所有匹配項的JSON數據,而是希望獲取具有id:2
的匹配項的JSON數據。我該如何使用以下代碼嘗試獲取它,但它獲取所有匹配項的JSON數據。
app.get('/api/matches/:match_id', (req, res) =>{
let match = req.params.id;
matches.find({match}).then(eachOne =>{
res.json(match);
});
});
在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;
您的代碼幾乎是正確的。 您只需要指定正確的查詢:
app.get('/api/matches/:match_id', (req, res) =>{
let match = req.params.match_id;
matches.findOne({id: parseInt(match)}).then(m =>{
res.json(m);
});
});
還要考慮url中的match_id
是一個字符串,因此您需要檢查它並將其轉換為數字(我使用parseInt
)
默認情況下,您必須使用bodyparser。
你做錯了
app.get('/api/matches/:match_id', (req, res) =>{
// instead of req.params.id write req.params.match_id
let match = req.params.match_id;
// when you write {match} there is nothing {id : match}
matches.find({match_id : match}).then(eachOne =>{
res.json(eachOne);
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.