Kingsley CA
Kingsley CA

Reputation: 11614

Mongoose - How to define 2 types for a field in the Schema

so in my payments model. I have a price field that can either take a payment object (currency, amount) or a "FREE" string. How do I define this in the model.

i.e.

price: { currency: "USD", amount: "100.00"}

or

price: "FREE"

So, how to I define this in my model, because this doesn't work:

...
price: { currency: String, amount: String } || String
...

Upvotes: 1

Views: 2545

Answers (1)

Shivam Pandey
Shivam Pandey

Reputation: 3936

You can use mixed schema type,

new Schema({
ofMixed:    [Schema.Types.Mixed],
})

But you have to mark it modified as mentioned in the docs

Since it is a schema-less type, you can change the value to anything else you like, but Mongoose loses the ability to auto-detect and save those changes. To tell Mongoose that the value of a Mixed type has changed, you need to call doc.markModified(path), passing the path to the Mixed type you just changed.

instead you can use schema.path() and look into this mongoose issue to get a better solution to avoid mixed type here.

Upvotes: 1

Related Questions