Schemas

In Mongoose, schemas are what we use to define our models. Visualize the schemas as the blueprints which are used to create the models. Using schemas, you can define much more than the simple blueprint of a MongoDB model. You can also take advantage of the built-in validation that Mongoose provides by default, adding static methods, virtual properties, and more.

The first thing we do while defining a schema for a model is build a list of every field we think we will need for a particular document. The fields are defined by type, and the standard data types you would expect are available, as well as a few others:

  • String: This type stores a string value.
  • Number: This type stores a number value, with restrictions.
  • Date: This type holds a date and time object.
  • Buffer: This type provides the storage for binary data. For instance, it can include images or any other files.
  • Boolean: This type is used to store a Boolean (true/ false) value.
  • Mixed: This is basically an unstructured object that can contain anything. Consider this when storing JSON type data or data that is arbitrary and
    can literally be any JSON representation. It doesn't need to be predefined.
  • ObjectID: This is typically used when you want to store the ObjectID of another document in a field, for example, when defining a relationship.
  • Array: This is a collection of other schemas (models).

Here is an example of a basic Mongoose schema definition:

const mongoose = require('mongoose'),
Schema = mongoose.Schema;

var Account = new Schema({
username: { type: String },
date_created: { type: Date, default: Date.now },
visits: { type: Number, default: 0 },
active: { type: Boolean, default: false }
});

Here, we define our schema for an Account collection. The first thing we do is require Mongoose and then define a Schema object using mongoose.Schema in our module. We define a schema by creating a new Schema instance with a constructor object that defines the schema. Each field in the definition is a basic JavaScript object with its type and then an optional default value.

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

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