Difference between Schema and Sub Schema in mongoose

Sun Jan 1, 2023

In Mongoose, a schema is a blueprint for a MongoDB collection and defines the documents' structure. On the other hand, a sub-schema is a smaller schema used to define a sub-section of a larger schema.

A schema can define fields of various types, such as strings, numbers, booleans, arrays, etc. It can also define validation rules, default values, and other options for each field.

A sub-schema is used to define a nested structure within a schema. This can be useful when you have a field that is an array of objects or objects with several properties, and you want to define a specific structure for those objects or properties.

For example, consider a schema for a "User" collection that has a field called "address" which is an object containing several properties such as street, city, and zip code. Instead of defining all the properties in the main User schema, you can use a sub-schema to determine the structure of the address object.

const addressSchema = new mongoose.Schema({ street: String, city: String, zip: Number }); const userSchema = new mongoose.Schema({ name: String, email: String, address: addressSchema });

In this example, the addressSchema is the sub-schema, and it is used to define the structure of the address field in the userSchema.

Additionally, sub-schemas can also be used to define nested arrays of objects, such as in the first example I provided, where I defined subSchema to use as an array inside the myArray field.

In summary, the main difference between a schema and a sub-schema in Mongoose is that a schema defines the structure of a MongoDB collection. In contrast, a sub-schema defines a nested structure within a schema.

DCT Academy
Full Stack Web Development training institute in Bangalore

Launch your GraphyLaunch your Graphy
100K+ creators trust Graphy to teach online
𝕏
Best MERN Full Stack Development Course | Bangalore | Offline | Online | 100% Placements | Training Institute | Front End Course | React JS Training | Online Course India 2024 Privacy policy Terms of use Contact us Refund policy