如何创建 Mongoose Schema 并将默认值设置为带有打字稿的数组?

How to create Mongoose Schema and set default to an array with typescript?

我正在尝试创建一个具有名为 'business' 的条目的架构,它应该是数组类型。

这是我试过的。

export interface IBusinessShort{
    savedOn: string;
}

export interface IUser {
    name: string;
    email: string;
    username: string;
    password: string;
    phoneNumber: string;
    avatar?: string;
    business: Array<IBusinessShort>;
}

const schema = new Schema<IUser>({
    name: { type: String, required: true },
    email: { type: String, required: true },
    username: { type: String, required: true },
    password: { type: String, required: true },
    phoneNumber: { type: String, required: true },
    avatar: String,
    business: { type: Array, default: []},
});

我做错了什么?

根据您的架构,您试图将默认值设置为空数组,但是,mongoose 已经定义了它。关于这点,那部分代码可以去掉。

Arrays are special because they implicitly have a default value of [] (empty array).

const ToyBox = mongoose.model('ToyBox', ToyBoxSchema);

console.log((new ToyBox()).toys); // []

参考:Mongoose - Arrays