如何使用AWS Amplify V5移除DynamoDB中的属性?
如何从DynamoDB项中移除GraphQL枚举类型属性?
我希望使用更新mutation从DynamoDB的项中移除属性。我的schema中定义了published: PUBLISHED,对应枚举类型enum PUBLISHED { YES },借此利用稀疏索引(sparse indexes)的优势。我该如何确保从DynamoDB项中移除published属性?
我的代码:
const updateJobListing = /* GraphQL */ ` mutation UpdateJobListing($input: UpdateJobListingInput!, $condition: ModelJobListingConditionInput) { updateJobListing(input: $input, condition: $condition) { published } } `; await API.graphql({ query: updateJobListing, variables: { input: { published: null, }, }, authMode: "AMAZON_COGNITO_USER_POOLS", });
我的错误:
{ "data": null, "errorInfo": null, "errorType": "Unauthorized", "locations": [{}], "message": "Unauthorized on [published]", "path": ["updateJobListing"] }
解决方案
1. 修复权限问题
错误提示Unauthorized on [published]说明当前认证用户没有修改published字段的权限,需要检查GraphQL schema的权限配置:
- 查看
JobListing类型上的@auth指令,确认update操作规则允许当前用户修改published字段。比如确保@auth的update规则没有限制该字段的访问,或明确包含对published字段的操作权限。
2. 确保字段支持移除操作
要通过设置null移除DynamoDB中的published属性,需满足两个条件:
- 字段可空:检查
JobListing类型定义,published字段不能带有!(非空修饰符)。如果当前是published: PUBLISHED!,需修改为published: PUBLISHED,重新部署GraphQL API。 - 默认移除逻辑生效:Amplify或AppSync生成的API默认支持“给可空字段设null时自动删除对应DynamoDB属性”的逻辑,确保你的API配置未覆盖此默认行为。
完成上述步骤后,重新执行update mutation即可成功移除published属性,同时保留稀疏索引特性——属性不存在时,该项不会出对应的稀疏索引中。
内容的提问来源于stack exchange,提问作者Luke
相关产品推荐
相关产品推荐

