Search code examples
javascriptnode.jsmongodbmongoosemongoose-schema

Set a limit for an array in mongoose schema


I'm trying to create a mongoose Schema and set one of its fields' type to be an Array

But I need to limit that array by default, which means if we tried to add a new Item to that array when it's filled with the limit count, it refuses to take this new item.

Let's say I need to set a product schema which will have prices, and it must contain just as most cases 3 prices only.

let Product = mongoose.model(
    "Product",
    new mongoose.Schema({
        username: { type: String, required: true },
        name: {type: String, required: true},
        description: String,

        prices: {type: Array, required: true, max_items: 3}

    })
)

All the idea is, Is there is a property to put instead of the max_items to maximize the possible items can be added to this array??

I think that I can put a limit property but I don't know if it's can work or not because I did a hard search I didn't find anyone talks about it.


Solution

  • You may use a custom validate() function: validate: [prices => prices.length <= 3, 'message'].

    This validates that there are no more than 3 documents, otherwise it returns 'message'

    https://mongoosejs.com/docs/api.html#schematype_SchemaType-validate