54

I have a user schema with mongoose in nodejs like this

userschema = mongoose.Schema({
    org: String,
    username: String,
    fullname: String,
    password: String,
    email: String
});

Except sometimes I need to add some more fields.

The main question is: Can I have optional fields in a monogoose schema?

Talha Awan
  • 4,573
  • 4
  • 25
  • 40
HarveyBrCo
  • 805
  • 1
  • 9
  • 17

2 Answers2

82

All fields in a mongoose schema are optional by default (besides _id, of course).

A field is only required if you add required: true to its definition.

So define your schema as the superset of all possible fields, adding required: true to the fields that are required.

JohnnyHK
  • 305,182
  • 66
  • 621
  • 471
  • 3
    Is it possible to set `required:true` on a couple of fields if and only if a third field has `required:true`? The use case for this is quite common... e.g. `hourlyRate` and `endDate` are required only if `isContractor` is a required field. – Web User Aug 08 '16 at 21:57
63

In addition to optional (default) and required, a field can also be conditionally required, based on one or more of the other fields.

For example, require password only if email exists:

var userschema = mongoose.Schema({
    org: String,
    username: String,
    fullname: String,
    password: {
        type: String,
        required: function(){
            return this.email? true : false 
        }
    },
    email: String
});
Talha Awan
  • 4,573
  • 4
  • 25
  • 40
  • not working with typescript it says: the "this" keyword is disallowed outside of a class body (no-invalid-this)tslint(1) :-( – Inzamam Malik Feb 20 '20 at 16:02
  • I am on a firebase function project and want the same things, even it works when I remove this "no-invalid-this" property from ts-lint file but is this correct to do so? – Inzamam Malik Feb 20 '20 at 16:03
  • @InzamamMalik I'm afraid I don't have much experience with typescript. Afaik, there are no hard and fast rules about most lint warnings, so I guess there should be no harm in removing the property. – Talha Awan Feb 21 '20 at 17:33
  • These kinds of required conditions in Mongoose are similar to check constraints on columns in ANSI standard SQL – Dennis G Allard Mar 27 '23 at 02:54