Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose schema optional fields

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?

like image 507
HarveyBrCo Avatar asked Jul 24 '14 19:07

HarveyBrCo


People also ask

Are Mongoose fields required by default?

It seems that the default value of the required attributes of each field in mongoose schema is false.

Can I set default value in Mongoose schema?

You can also set the default schema option to a function. Mongoose will execute that function and use the return value as the default.

What is Mongoose schema types ObjectId?

ObjectId . A SchemaType is just a configuration object for Mongoose. An instance of the mongoose. ObjectId SchemaType doesn't actually create MongoDB ObjectIds, it is just a configuration for a path in a schema.

What does $Set do in Mongoose?

The $set operator replaces the value of a field with the specified value.


2 Answers

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.

like image 93
JohnnyHK Avatar answered Oct 11 '22 16:10

JohnnyHK


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 }); 
like image 43
Talha Awan Avatar answered Oct 11 '22 17:10

Talha Awan