只通过GET请求拉取对象的某些部分

时间:2014-11-25 15:45:40

标签: javascript angularjs node.js mongodb mongoose

在我的网络应用程序的主页上,我向我的API发出GET请求,以便在我的数据库中提取当前的体育场列表。我需要每个Stadium对象的某些部分(名称,城市,州,prim_hex,sec_hex,活动)。问题是这些体育场物体还包含一张照片"阵容中有成千上万的照片'对象。由于我的get请求会撤回所有Stadium对象,我的主页需要5-10秒才能加载(由于大型"照片"数组)。

我的相关代码如下。我将如何改变我的GET请求以仅撤回我需要的部分(换句话说,不要拉入"照片"主页加载上的数组)?

示例Stadium对象:

{
"_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": [...]
}

' routes.js'中的当前GET代码在我的nodejs服务器上:

// 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)代码是需要更改的代码,但我不确定如何正确地修改它以仅拉取每个Stadium对象的某些部分。

2 个答案:

答案 0 :(得分:1)

要硬编码:

Stadium.find({}, "-photos", function (err, stadia) {
    // do stuff
});

OR(我经常使用的方法):

var query = Stadium.find();
query.select("-photos");
query.exec(function (err, stadia) {
    // do stuff
});

第二种形式允许您构建和添加查询,而不需要在Model.find()

中放置一个大对象

查看the API docs for Model.findquery.select

答案 1 :(得分:1)

首先,我将重新定义GET / api / stadia的数据响应模式。我不会在数据结构中提供一系列照片,而只会为照片提供一系列唯一ID。我假设照片可以通过某种唯一标识符单独引用。

{
    "_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
    ...
});
相关问题