dynamoose - 创建 shcemas 时出现 Dynamoose 问题“无法创建预先存在的表”或“无法对不存在的表执行操作”
问题描述
我正在为我的 dynamodb 设计使用单一表方法。
看看这里(单表结构示例)。无需阅读所有页面。这个想法是将几种不同类型的实体存储在同一个表中。(例如,订单、产品、客户等)。
我使用 dynamoose,我有以下模式:
const schema_1 = {
PK: { type: String, hashKey: true },
SK: { type: String, rangeKey: true },
someAttribute: { type: String, required: true }
};
const schema_2 = {
PK: { type: String, hashKey: true },
SK: { type: String, rangeKey: true },
someOtherAttribute: { type: String, required: true }
};
我使用以下内容创建表:
const ExampleModel = dynamoose.model('TestTable', schema_1);
const AnotherModel = dynamoose.model('TestTable', schema_2, {create: false});
问题是,当我运行此代码时,我得到一个无法对不存在的表执行操作的错误。
注意:该表已创建,但也引发了错误。
但是,如果我在两次通话之间添加睡眠时间,问题就会消失。
const ExampleModel = dynamoose.model('TestTable', schema_1);
await new Promise(resolve => setTimeout(resolve, 1000));
const AnotherModel = dynamoose.model('TestTable', schema_2, {create: false});
(注意:我在异步代码中运行它- 以下是完整代码)
我认为这种等待不应该存在,并且在我运行代码的环境中,使模型创建异步产生另一个错误,因为需要模式的代码是在初始化之前执行的。
希望您能够帮助我。
完整代码在这里:
let testFunction = async () => {
dynamoose.aws.sdk.config.update({
region: 'local.region',
});
dynamoose.aws.ddb.local();
const schema_1 = {
PK: { type: String, hashKey: true },
SK: { type: String, rangeKey: true },
someAttribute: { type: String, required: true }
};
const schema_2 = {
PK: { type: String, hashKey: true },
SK: { type: String, rangeKey: true },
someOtherAttribute: { type: String, required: true }
};
const ExampleModel = dynamoose.model('TestTable', schema_1);
//await new Promise(resolve => setTimeout(resolve, 1000));
const AnotherModel = dynamoose.model('TestTable', schema_2, {create: false});
}
testFunction();
所需的依赖项是:
- 发电机:
npm install dynamoose
- 本地 dynamodb:(见此页)
java -Djava.library.path=./DynamoDBLocal_lib -jar DynamoDBLocal.jar -sharedDb -inMemory
解决方案
把答案也放在这里(感谢查理在评论中添加链接)
此代码在技术上应该失败。不应允许您创建两个具有相同名称的模型。
我建议测试 v2.3.0-beta.1,它增加了对多表设计的更好支持。您的代码可能是:
const schema_1 = {
PK: { type: String, hashKey: true },
SK: { type: String, rangeKey: true },
someAttribute: { type: String, required: true }
};
const schema_2 = {
PK: { type: String, hashKey: true },
SK: { type: String, rangeKey: true },
someOtherAttribute: { type: String, required: true }
};
const ExampleModel = dynamoose.model('TestTable', [schema_1, schema_2]);
留下其他评论以供将来阅读(在最终 v2.3.0 发布之前,当前的解决方案对我有用)。
由于我使用此代码在本地环境(节点 + jest)上进行测试,我最终使用“@shelf/jest-dynamodb”(看这里)在测试运行时创建数据库,我可以避免在代码上创建模式. 所以两个模型定义都有 {create: false}。