【发布时间】:2018-01-21 09:12:52
【问题描述】:
我正在使用 NodeJS 和 mongodb 向 API 端点发出 get 请求。 在 app.js 中:
app.get('/api/matches', (req, res) =>{
//console.log('Get matches..');
matches.find({}).then(eachOne => {
res.json(eachOne);
});
});
以上代码给出了 JSON 响应,如下所示:
现在我想使用 app.get() 方法获取特定匹配的 JSON 响应,但每当我使用下面的代码时,它总是为不同的 URL 返回 id:1 的 JSON 数据,例如 http://localhost:5000/api/matches/3 或 http://localhost:5000/api/matches/6
app.get('/api/matches/:match_id', (req, res) =>{
let match = req.params.id;
matches.findOne({match_id: match}).then(m =>{
res.json(m);
});
});
以上两个 URL 提供相同的 JSON 数据,但它们应该提供不同的 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": ""
}
在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;
【问题讨论】:
-
检查你是否传递了 GET 请求中生成的 user_defined 或 mongoDb。
-
我已经编辑了我的问题,请查看matches.js文件
-
你有很多相同id的文档吗?
-
@Saravana No id is unique id=1,2,3,4,5,...577
-
@Saravana 我已经回答了我的问题,请查看。
标签: javascript json node.js mongodb