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

标签 javascript node.js rest api web

基本上,我只想在向 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": "johndoe@johndoe.com",
    "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 请求来实现此目的?

谢谢

最佳答案

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

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

关于javascript - 在 GET 请求中仅发送部分数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44098388/

相关文章:

javascript - AngularJS:如何在 HTML 中显示带有两个 ng-repeats 的对象值

javascript - Sequelize 无法创建表,但是当我在 MySQL CLI 中运行它时它可以工作

node.js - loopback 4中如何编写单元测试用例

javascript - 无法导入 JavaScript 类。类型错误 : "class" is not a constructor

java - 导出 CSV 文件 - JAX RS - REST - AJAX

AngularJS 读取 web.config 值

.net - 超出 HttpClient 缓冲区大小限制

javascript - TypeScript Array.prototype.map 声明

javascript - 在javascript中循环以禁用字段

node.js - 为什么在某些情况下,某些版本的 Node.js 上 process.env._ 未定义?