Why does mongoose have both schemas and models
Schemais an object that defines the structure of documents in a MongoDB collection. It describes the shape and data types, serving as the blueprint or template for data. Using , we can define precisely which fields a document should have, their data types, whether they are required, default values, and validation rules.For example, if we have a user collection, we might define a like this:In this example, defines that users should have , , , and fields, with types and , and except for which has a default value, the others are required.Modelis a constructor or class compiled from , whose instances represent individual documents in the database. Through , we can perform actual CRUD operations (Create, Read, Update, Delete) on the database.Continuing the previous example, we would create a like this:Here, we create a named associated with . This means we can now create new users, query users, update users, and delete users:Why Both Schema and Model?and are separated because they serve distinct roles. is responsible for defining the structure and rules of data, while provides an interface for interacting with the database.Separating these two enhances Mongoose's design by making it more flexible and modular. You can define your data structure in one place (), and then create one or more instances where needed to handle data. This separation also facilitates maintenance and scalability, as data structures may change frequently, and with separation, we can modify without affecting the that uses it.Additionally, Mongoose allows us to define instance methods, static methods, and virtual properties within , enabling us to call these methods on instances, making data operations more convenient and efficient.