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

如何在Mongoose Schema中定义二维数组并设置预置默认值

Mongoose二维数组字段默认值配置方案

问题场景

需要在用户Schema中定义规格为2*2的二维字符串数组favorite字段,初始实现代码如下:

import { Document, Schema, model } from "mongoose";
export interface IUserModel extends Document {
    favorite:string[][];
}
const UserSchema = new Schema<IUserModel>({
favorite: {
        type: [{String}]
    }})

export const UserModel = model<IUserModel>("UserModel", UserSchema, "Users"); // model name, schema class, collection name

需求是为该字段配置预置默认值[["hello","world"],["1","2"]],技术栈为Angular、MongoDB、Node.js。

问题根因

初始代码存在两个问题:

  • 类型声明错误:type: [{String}]仅声明了一维字符串数组结构,和TS定义的string[][]二维数组类型不匹配
  • 缺少默认值配置项:Mongoose Schema字段需要显式声明default属性才会在文档创建时自动填充预置值

正确实现代码

修正后的Schema定义如下,同时可选增加尺寸校验保证字段始终符合2*2的规格要求:

import { Document, Schema, model } from "mongoose";
export interface IUserModel extends Document {
    favorite: string[][];
}
const UserSchema = new Schema<IUserModel>({
    favorite: {
        // 声明为二维字符串数组,和TS类型定义对齐
        type: [[String]],
        // 配置预期静态默认值
        default: [["hello", "world"], ["1", "2"]],
        // 可选:增加格式校验,强制字段始终为2*2规格,不符合规则的写入会抛出校验错误
        validate: {
            validator: (value: string[][]) => {
                return value.length === 2 && value.every(row => row.length === 2 && row.every(item => typeof item === "string"));
            },
            message: "favorite字段必须为2行2列的字符串二维数组"
        }
    }
})

export const UserModel = model<IUserModel>("UserModel", UserSchema, "Users");

效果说明

  • 新建User文档时如果未手动传入favorite字段值,Mongoose会自动填充配置的默认值
  • 该配置和前端Angular框架无耦合,仅在Node.js端的Mongoose层生效,兼容Mongoose 6.x、7.x、8.x主流版本
  • 如果不需要强制固定数组尺寸,删除validate配置项即可

内容的提问来源于stack exchange,提问作者George ak

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 10:36:20