You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

创建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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 15:10:01