There's more...

It's useful to mark the fields as required to avoid having "null" values being saved in the database. An alternative is to set default values for the fields that are not explicitly defined in the creation time of the document. For instance:

      const UserSchema = new Schema({ 
          name: { 
              type: string, 
              required: true, 
              default: 'unknown', 
          } 
      }) 

When a new document is created, if no path or property name is assigned, then it will assign the default value defined in the schema type option default.

The schema type default option can also be a function. The value returned by calling this function is assigned as the default value.

Sub-documents or arrays can also be created by just adding brackets when defining the schema type. For instance:

      const WishBoxSchema = new Schema({ 
          wishes: { 
              type: [String], 
              required: true, 
              default: [ 
                  'To be a snowman', 
                  'To be a string', 
                  'To be an example', 
              ], 
          }, 
      }) 

When a new document is created, it will expect an array of strings in the wishes property or path. If no array is provided, then the default values will be used to create the document.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.144.248