Dipanshu Mahla
Dipanshu Mahla

Reputation: 152

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

I am trying to create a Schema that has an entry named 'business' and it should be of type array.

This is what I have tried.

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: []},
});

What am I doing wrong here?

Upvotes: 1

Views: 2073

Answers (1)

Nelson Faria
Nelson Faria

Reputation: 71

According to your schema, you are trying to set the default as an empty array, however, mongoose is already defining it. Regarding this, that part of the code can be removed.

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

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

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

Reference: Mongoose - Arrays

Upvotes: 3

Related Questions