如何在MongoDB中创建嵌套层级的Map Schema结构?
解决方案
这个结构在MongoDB中完全可行,错误根源是你定义嵌套Map的方式不符合Mongoose Schema的规则。
正确的Schema写法
需要明确每一层Map的of类型:外层Map的value是存储月份的内层Map,内层Map的value是包含cards数组的对象结构。可以通过分层定义Schema来实现:
// 定义卡片的子Schema const CardSchema = new Schema({ name: String, amount: Number, date: Date }); // 定义月份对应的结构Schema const MonthDataSchema = new Schema({ cards: [CardSchema] }); // 最终的动态年份Schema const DynamicSchema = new Schema({ year: { type: Map, // 内层Map的value类型为MonthDataSchema of: new Schema({ type: Map, of: MonthDataSchema }) } });
也可以用更简洁的内联写法:
const DynamicSchema = new Schema({ year: { type: Map, of: { type: Map, of: { cards: [{ name: String, amount: Number, date: Date }] } } } });
示例合法请求负载
按照正确的Schema,你可以提交如下格式的数据:
{ "year": { "2022": { "january": { "cards": [ { "name": "购物卡", "amount": 150, "date": "2022-01-10T20:30:00.000Z" } ] }, "february": { "cards": [ { "name": "餐饮卡", "amount": 200, "date": "2022-02-15T20:30:00.000Z" } ] } }, "2023": { "march": { "cards": [ { "name": "交通卡", "amount": 300, "date": "2023-03-20T20:30:00.000Z" } ] } } } }
关键注意点
- 之前的错误是因为你把
month字段直接写在了year的Map配置项中,这是错误的写法:Map类型的Schema配置只需要指定type和of,具体的月份字段应该作为内层Map的key存在。 - 每一层Map的
of必须明确对应的数据类型,不能混淆数组和Map的定义(你之前写的of: [Map]是错误的,应该是of: Map或者嵌套的Schema)。
内容的提问来源于stack exchange,提问作者Vanga Kiran Kumar Reddy
相关产品推荐
相关产品推荐

