Definition | A Model in Mongoose is a constructor function for creating documents and interacting with a MongoDB collection. It represents a MongoDB collection and is used to define the schema. | A Document in Mongoose is an instance of a model, representing a single record in the MongoDB collection. |
Purpose | Models provide the interface for interacting with the collection (e.g., querying, creating, updating, deleting). | Documents represent individual records in the MongoDB collection that adhere to the schema. |
Type | A Model is a constructor function that is used to create documents. | A Document is an instance created using a Model. |
Methods | Models have static methods like find() , create() , update() , remove() . | Documents have instance methods like save() , updateOne() , remove() . |
Schema Binding | A Model is tied to a Schema that defines the structure of the documents in the MongoDB collection. | A Document is an instance of a Model, meaning it follows the schema defined by the associated Model. |
Operations | Models perform operations at the collection level (e.g., fetching, creating, and updating multiple documents). | Documents perform operations at the instance level (e.g., saving or updating a specific record). |
Persistence | Models do not directly persist data to MongoDB but serve as a blueprint for creating and manipulating documents. | Documents are persisted in MongoDB as individual records in the collection. |
Use Case | Models are used for querying the database, creating new records, and performing bulk operations. | Documents are used to represent and manipulate individual records from the database. |
Creation | A Model is created by using mongoose.model('ModelName', schema) and is not an instance of a document. | A Document is created by using a Model's constructor, e.g., new Model() to instantiate a document. |
Example | const User = mongoose.model('User', userSchema); | const newUser = new User({ name: 'John', age: 30 }); |
Field Access | A Model defines the structure and field types of the collection but does not hold data. | A Document holds data corresponding to the fields defined by its Model. |
Static Methods | Models have static methods to query, update, or delete records. | Documents only have instance methods for operations like save() or remove() . |
Validation | Models can be used for validation before saving or updating data. | Documents are validated when performing actions like save() , ensuring data adheres to the schema. |
Example Method Usage | User.findOne({ name: 'John' }) | newUser.save() |