DynamoDB更新Date类型字段报错:Unsupported type passed求助
解决DynamoDB更新时Date类型属性报错问题
问题重现
创建文档时date属性(new Date())可正常插入:
table.create("User", { accountName: "johndoe", email: "test@test74.test", date: new Date(), // Date is inserted without any problem username: "johndoe", firstName: "John", lastName: "Doe" }).then(console.log).catch(console.error)
但更新该属性时抛出错误:
Error: Unsupported type passed: Mon Oct 31 2022 16:15:25 GMT+0100 (Central European Standard Time). Pass options.convertClassInstanceToMap=true to marshall typeof object as map attribute.
更新代码:
table.update("User", {pk: "johndoe"}, { set: { date: new Date() } }).catch(console.error)
解决方案
1. 将Date转换为ISO格式字符串
直接把Date对象转为DynamoDB原生支持的字符串类型,这是最简单的处理方式:
table.update("User", {pk: "johndoe"}, { set: { date: new Date().toISOString() } }).catch(console.error)
读取时可通过new Date(dateString)将字符串转回Date对象。
2. 使用AWS SDK工具序列化Date对象
借助@aws-sdk/util-dynamodb包的marshall函数,将Date转为DynamoDB标准的AttributeValue格式:
import { marshall } from "@aws-sdk/util-dynamodb"; const updatedDate = marshall({ date: new Date() }).date; table.update("User", {pk: "johndoe"}, { set: { date: updatedDate } }).catch(console.error)
3. 启用convertClassInstanceToMap选项
按照错误提示,在更新操作的配置中添加该选项(注意:此选项会将所有类实例转为Map类型,需确认是否影响其他属性):
table.update("User", {pk: "johndoe"}, { set: { date: new Date() } }, { convertClassInstanceToMap: true }).catch(console.error)
内容的提问来源于stack exchange,提问作者klaucode
相关产品推荐
相关产品推荐

