在 GET 请求中仅发送部分数据

问题描述 投票:0回答:1

基本上,我只想在向 REST API 发出 GET 请求时发回一些数据。我的 GET 请求代码:

router.get('/user/all', function(req, res, next){
    User.find({name: req.query.name}).then(function(assets){
        res.send(assets);
    });
});

返回:

[
  {
    "_id": "546b454b5634563b546",
    "name": "John Doe",
    "email": "[email protected]",
    "phoneNo": "00000000000",
    "active": true,
    "__v": 0,
    "assets": [
      {
        "name": "house",
        "location": {
          "_id": "592190ce29f12e179446d837",
          "coordinates": [
            -81.5,
            24.1
          ],
          "type": "point"
        },
        "_id": "592190ce29f12e179446d836"
      }
    ]
  }
]

但我只希望它返回:

[
   {
     "name": "house",
     "location": {
     "_id": "592190ce29f12e179446d837",
     "coordinates": [
       -81.5,
        24.1
      ],
      "type": "point"
    },
    "_id": "592190ce29f12e179446d836"
  }
]

如何更改 API 请求来实现此目的?

javascript node.js rest
1个回答
1
投票

如果您只想返回资产,请尝试以下操作:

router.get('/user/all', function(req, res, next){
    User.find({name: req.query.name}).then(function(assets){
        res.send(assets.map(function(x) {return x.assets;}))
    });
});
© www.soinside.com 2019 - 2024. All rights reserved.