在我的web应用程序的主页上,我向我的API发送一个GET请求,以便在我的数据库中提取一个当前的体育场列表。我需要每个体育场物体的某些部分(名称,城市,州,prim_hex,sec_hex,活动)。问题是这些体育场的物体也包含一个“照片”数组,里面有成千上万的“照片”对象。由于我的get请求拉回所有体育场对象,我的主页需要5-10秒来加载(由于大的“照片”数组)。
我的相关代码在下面。我将如何改变我的GET请求,只收回我需要的部分(换句话说,不要在主页加载时插入“照片”数组)?
示例体育场对象:
{
"_id": {
"$oid": "54148f29e4b01927d54d26bc"
},
"name": "High Point Solutions Stadium",
"division": "East",
"team": "Rutgers Scarlet Knights",
"city": "Piscataway",
"city_norm": "Piscataway",
"state": "NJ",
"loc": [
-74.465573,
40.513676
],
"loc_id": 300149,
"prim_hex": "#d21034",
"sec_hex": "#000000",
"logo": "rutgers",
"active": false,
"photos": [...]
}当前nodejs服务器上“routes.js”中的GET代码:
// get all stadia
app.get('/api/stadia', function(req, res) {
// use mongoose to get all stadia in the database
Stadium.find(function(err, stadia) {
// if there is an error retrieving, send the error. nothing after res.send(err) will execute
if (err)
res.send(err)
res.jsonp(stadia); // return all stadia in JSON format
});
});我相信res.jsonp(stadia)代码是需要修改的,但我不知道如何正确地修改它以只拉出每个体育场物体的某些部分。
发布于 2014-11-25 20:19:55
要对其进行硬编码:
Stadium.find({}, "-photos", function (err, stadia) {
// do stuff
});或者(我经常使用的方法):
var query = Stadium.find();
query.select("-photos");
query.exec(function (err, stadia) {
// do stuff
});第二种形式允许您构造和添加查询,而无需在Model.find()中插入一个大对象。
看看Model.find的API文档和query.select
发布于 2014-11-25 21:39:20
首先,我将重新定义GET /api/stadia的数据响应的模式。与其在数据结构中提供照片数组,我只为照片提供一个唯一的I数组。我想这些照片可以被某种独特的标识符单独引用。
{
"_id": {
"$oid": "54148f29e4b01927d54d26bc"
},
... other properties ...
"active": false,
"photoIDs": [ "ID-12345", "ID-67890" ]
}然后,我会添加一个独特的网址,以要求照片。
app.get('/api/stadia/photo/:photoID', function(req, res) {
var photoID = req.param( "photoID" );
// now get that one photo from mongodb and return it
...
});或者,如果您更喜欢为所有照片提供一个GET请求的更简单的界面,您只需为其创建一个单独的URL:
app.get('/api/stadia/photos', function(req, res) {
// respond with the array of all the photos
...
});https://stackoverflow.com/questions/27131002
复制相似问题