【问题标题】:How to create Mongoose Schema and set default to an array with typescript?如何创建 Mongoose Schema 并将默认设置为带有 typescript 的数组?
【发布时间】:2022-01-07 16:36:26
【问题描述】:

我正在尝试创建一个包含名为“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: []},
});

我在这里做错了什么?

【问题讨论】:

    标签: typescript mongodb mongoose mongoose-schema


    【解决方案1】:

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

    数组之所以特殊,是因为它们隐含的默认值为 [](空数组)。

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

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

    参考:Mongoose - Arrays

    【讨论】:

    • 感谢您的回答。只需要写业务:{ type: Array()},你能解释一下为什么我必须在最后使用'()'
    猜你喜欢
    • 2016-02-19
    • 2019-03-27
    • 2015-11-26
    • 2015-05-25
    • 1970-01-01
    • 2019-10-01
    • 1970-01-01
    • 2017-08-01
    • 2018-07-26
    相关资源
    最近更新 更多