我想从所有匹配中获取特定的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数据,而是希望得到匹配的JSON数据id:2
我怎么能得到我尝试使用下面的代码,但它获得所有匹配的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;
答案 0 :(得分:1)
您的代码几乎是正确的。您只需指定正确的查询:
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
)
答案 1 :(得分:0)
默认情况下,您必须使用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);
});
});