创建DynamoDB用户模型时遇SchemaError:playlist无映射Schema
解决Dynamoose中
SchemaError: No map schema given for attribute: playlist错误 问题场景
使用Dynamoose构建用户模型时,声明嵌套的playlist属性后,调用User模型始终抛出错误:SchemaError: No map schema given for attribute: playlist,相关代码如下:
原/models/v2/schema.js代码
const dynamoose = require('dynamoose'); const schemaOpt = { saveUnknown: true, timestamps: true }; const playlistSchema = new dynamoose.Schema({ "description": String, "id": String, "name": String, "image": String }, schemaOpt); const userSchema = new dynamoose.Schema({ "pk": { type: String, hashKey: true }, "sk": { type: String, rangeKey: true }, "playlist": { type: Object, schema: playlistSchema } }, schemaOpt); module.exports = userSchema;
原/models/v2/user代码
'use strict'; const dynamoose = require('dynamoose'); const userSchema = require('./schema'); const UserModel = dynamoose.model("User", userSchema); exports.User = UserModel;
错误原因
Dynamoose中,type: Object的属性不支持schema配置项。当给Object类型属性指定schema时,Dynamoose会误认为你要定义Map类型(需要明确的map schema),但实际你是想定义嵌套对象结构,因此抛出错误。
修正方案
直接将playlist的类型设置为预先定义好的playlistSchema,不需要额外的type: Object配置。修改后的schema.js代码如下:
const dynamoose = require('dynamoose'); const schemaOpt = { saveUnknown: true, timestamps: true }; const playlistSchema = new dynamoose.Schema({ "description": String, "id": String, "name": String, "image": String }, schemaOpt); const userSchema = new dynamoose.Schema({ "pk": { type: String, hashKey: true }, "sk": { type: String, rangeKey: true }, // 直接使用playlistSchema作为属性类型 "playlist": playlistSchema }, schemaOpt); module.exports = userSchema;
也可以显式声明type字段,效果一致:
"playlist": { type: playlistSchema }
验证
修改后重新导入User模型,即可正常使用,不会再抛出SchemaError。
内容的提问来源于stack exchange,提问作者Kean Allen Imam
相关产品推荐
相关产品推荐

