Automattic / mongoose

MongoDB object modeling designed to work in an asynchronous environment.
https://mongoosejs.com
MIT License
27k stars 3.85k forks source link

Add a nullable field, its not same as "required" #14421

Open yhojann-cl opened 8 months ago

yhojann-cl commented 8 months ago

Prerequisites

🚀 Feature Proposal

The "required" parameter of a model in mongoose defines whether the document attribute is required, but in turn it plays a double role, if it is required and if the value is null.

I think that both options should be defined separately since, for example, I can not require said field and have a value of type "undefined" and I can also require the field as mandatory but it can be null (that is, it must be defined but not necessarily with a value). Json schema works in a similar way since the "required" parameter only works to define whether it is required or not, content validation is done separately.

It would be less difficult to work with if mongoose had these two parameters separately, one called "required" and another "nullable", you could even have another one that says "canEmpty" that indicates whether an array, object or string can be empty and avoid having to perform validations by functions and regular expressions.

Currently, according to the official documentation, this can be done through custom functions, but I think that all of us could avoid those functions if those parameters existed and include others from json schema like as "pattern".

Motivation

Avoid using functions in each validation of null, empty and undefined data in each model to be created.

Example

From:

module.exports = mongoose.model('user',
    new mongoose.Schema({
        lastName: {
            type: String,
            required: true,
            validate: val => ((val === null) || !!val.match(/^[a-zA-Z]{1,12}$/))
        },
    }));

Simplificate to:

module.exports = mongoose.model('user',
    new mongoose.Schema({
        lastName: {
            type: String,
            required: true,
            nullable: true,
            pattern: /^[a-zA-Z]{1,12}$/,
        },
    }));
vkarpov15 commented 8 months ago

Mongoose generally treats null and undefined as interchangeable, because undefined values end up stored as null in MongoDB anyway.

I can see the benefit of supporting something like required: 'nullable' to have a field be required, but allow null values. However, how should that handle undefined values? Like new User({ lastName: undefined })?

pauldraper commented 5 days ago

@vkarpov15 "undefined" properties should be omitted from the document.