如何从json-server中的数组的单个对象中检索子对象?

问题描述

我使用 json-server 作为模拟后端来检索单个对象的子对象。
父表 sentinel 和子表 sensor

the table sentinel

the sensor table

如您所见,sensors一个数组,而 sentinel一个对象。
我使用了 http://localhost:3000/sentinel?_embed=sensors 但响应不是我所期望的,因为我想要 sensors: [{id: 1},{id: 2},ecc]

[3]: https://i.stack.imgur.com/tTugQ.png

official documentation 显示了检索两个表的两种方法
_embed包括子项)和 _expand(包括父项)。

我怎样才能达到这个结果?

解决方法

鉴于 sentineldb.json 中的单个对象,并且您不能拥有多个 sentinel,我不清楚您的查询与检索所有传感器有何不同sentinelId=10

/sensors?sentinelId=10

事实上,如果你尝试这个 API:

/sentinel/10/sensors

它会起作用,因为 json-server 将 url 完全重写为上一个查询。

如果由于某种原因您不想直接在查询中使用 sentinel id,另一种选择是使用 json-server 作为模块并使用您需要的逻辑定义自定义路由。下面是一个基本示例,它公开 /sentinel/sensors API 并检索 sentinel 数据以及 sentinelId 等于当前 sentinel id 的传感器:

const jsonServer = require('json-server');
const server = jsonServer.create();
const router = jsonServer.router('./db.json');
const db = router.db;

server.use(jsonServer.bodyParser);
server.get('/sentinel/sensors',(req,res) => {
  const sentinel = db.get('sentinel').value();
  const sensors = db
    .get('sensors')
    .filter({ sentinelId: sentinel.id })
    .value();
  res.send({ ...sentinel,sensors: sensors });
});
server.use(router);
server.listen(3001,() => {
  console.log('Mock server is running on port ' + 3001);
});

那会给你这样的回应:

{
  "id": 10,"name": "Sentinel","sensors": [
    {
      "id": 1,"sentinelId": 10
    },{
      "id": 2,"sentinelId": 10
    }
  ]
}

这是一个stackblitz

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...