如何使用Dynamoose实现多模型共享单个数据表?
如何用Dynamoose让多个模型共享单个数据表
当然可以!Dynamoose完全支持多个模型共享同一张DynamoDB数据表,刚好匹配你想用type作为哈希键、id作为范围键区分不同实体的需求。下面是具体的实现方案和代码示例:
核心思路
我们可以先定义包含**共享键(hashKey和rangeKey)**的基础Schema,然后让每个业务模型继承这个基础Schema并扩展自己的专属字段,最后创建模型时指定同一个表名即可。
代码实现
首先,统一表名和基础Schema:
const dynamoose = require("dynamoose"); const TABLE_NAME = process.env.CONTENT_TABLE; // 定义基础Schema:包含所有模型共享的hashKey和rangeKey const baseSchema = new dynamoose.Schema({ type: { type: String, hashKey: true }, // 用来区分不同模型的哈希键 id: { type: String, rangeKey: true } // 每个实体的唯一范围键 }, { throughput: { read: 5, write: 5 } // 替换成你的实际吞吐量配置 });
接下来创建你的Courses模型,继承基础Schema并扩展课程专属字段:
// 课程模型 const Courses = dynamoose.model(TABLE_NAME, new dynamoose.Schema({ ...baseSchema.obj, // 继承基础的hashKey和rangeKey department: { type: String }, description: { type: String }, image: { type: String }, name: { type: String } }, { throughput: baseSchema.options.throughput // 复用基础Schema的吞吐量配置 }));
假设你还有另一个模型(比如Lessons课时模型),用同样的方式创建:
// 课时模型(共享同一张表) const Lessons = dynamoose.model(TABLE_NAME, new dynamoose.Schema({ ...baseSchema.obj, courseId: { type: String }, // 关联课程的ID duration: { type: Number }, // 课时时长 title: { type: String } // 课时标题 }, { throughput: baseSchema.options.throughput }));
关键注意事项
- 固定模型的
type值:每个模型对应的文档,type字段要设置固定值(比如课程的type都是"course",课时的都是"lesson"),这样才能通过type过滤出对应模型的数据。 - 查询示例:查询特定模型的数据时,只需指定对应的
type值即可:// 查询所有课程 const allCourses = await Courses.query("type").eq("course").exec(); // 查询单个课程 const targetCourse = await Courses.get({ type: "course", id: "CS101" }); - 表初始化:如果表还未创建,Dynamoose会根据第一个创建的模型Schema生成表结构,后续模型的额外字段会自动适配DynamoDB的动态属性特性,无需额外操作。
内容的提问来源于stack exchange,提问作者coherence
相关产品推荐
相关产品推荐

