How to use Nested Schemas In Mongoose
- Nested schemas are the technique that helps us to create complex data structures by putting one schema inside another.
- The purpose of this is to explain the connections among the various data types.
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const addressSchema = new Schema({
street: String,
city: String,
country: String
});
const userSchema = new Schema({
username: String,
email: String,
address: addressSchema
});
const UserModel = mongoose.model('User', userSchema);
Output:
Similar to basic schema registration, there won’t be direct output from registering the schema. It sets up the structure for the UserModel, enabling interactions with user data containing nested addresses.
Explanation:
- We define a schema for an address with fields street, city, and country.
- Then, we define a user schema with fields username, email, and address, where address is of type addressSchema.
How to Register Schema in Mongoose?
In Mongoose, schema registration is a crucial step in defining the structure of our MongoDB documents. In this article, We will go through the process of registering a schema in Mongoose by providing various methods with implementation to efficiently manage our data models.