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

Only pull certain parts of objects through GET request

本文关键字:些部 取对象 GET 请求      更新时间:2023-09-26

在我的网络应用程序的主页上,我向我的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)代码是需要更改的,但不确定如何正确更改它以仅提取每个体育场对象的某些部分。

要硬编码:

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()

查看 Model.find 和 query.select 的 API 文档

首先,我将重新定义 GET/api/stadia(英语:

GET/api/stadia)数据响应的模式。我不会在数据结构中提供照片数组,而是只为照片提供一组唯一 ID。我假设照片可以通过某种唯一标识符单独引用。

{
    "_id": {
        "$oid": "54148f29e4b01927d54d26bc"
    },
    ... other properties ...
    "active": false,
    "photoIDs": [ "ID-12345", "ID-67890" ]
}

然后我会添加一个不同的 url 来请求照片。

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
    ...
});