You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Dynamoose(Node.js)操作DynamoDB一对多关系:如何查询Table对应所有Reservation

解决方案

核心逻辑

Dynamoose 不支持自动反向关联查询,你可以直接过滤Reservation表的tableId字段实现需求,该字段本质存储的就是对应Table表的主键(tableId)值。

基础实现代码

1. 直接查询某桌台的所有预约

你只需要拿到目标桌台的tableId值,传入预约表的查询条件即可:

// 示例:查询tableId为T001的桌台对应的所有预约
reservationModel.scan("tableId").eq("T001").exec()
  .then(reservations => {
    // reservations 即为当前桌台的所有预约记录
    console.log("桌台预约记录:", reservations);
  })
  .catch(err => console.error("查询失败:", err));

2. 同时返回桌台信息+对应预约(async/await写法,可读性更高)

async function getTableReservations(targetTableId) {
  // 先查询桌台基础信息
  const table = await tableModel.get(targetTableId);
  if (!table) throw new Error("目标桌台不存在");
  // 再查询该桌台关联的所有预约
  const reservations = await reservationModel.scan("tableId").eq(targetTableId).exec();
  
  return {
    tableInfo: table,
    reservationList: reservations
  };
}

// 调用示例
getTableReservations("T001")
  .then(data => console.log(data))
  .catch(err => console.error(err));

性能优化建议

上面的实现用了scan操作,会全表扫描预约表,数据量大的时候性能很差,建议给Reservation表的tableId字段加全局二级索引(GSI),之后用query替代scan,查询效率提升明显。

索引配置示例

修改预约表的Schema:

const reservationSchema = new Schema ({
    id: {
        type: Number,
        required: true,
        unique: true,
        hashKey: true
    },
    tableId: {
      type: table,
      // 新增全局二级索引配置
      index: {
        name: "tableId-index",
        global: true
      }
    },
    date: {
        type: String
    }
});

索引查询代码

// 使用GSI查询,性能远高于全表扫描
const reservations = await reservationModel.query("tableId").eq(targetTableId).using("tableId-index").exec();

内容的提问来源于stack exchange,提问作者Nistha Adhikari

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 11:24:07