In Mongoose, a schema defines the structure of a document or record in a MongoDB collection. It defines the fields, their types, their default values, and any validation rules that should be applied to the data.
A model, on the other hand, is a class that represents a MongoDB collection. It is created by compiling a schema. It allows you to interact with a MongoDB collection in a more intuitive way by providing an interface for querying, inserting, updating, and deleting documents in the collection.
In short, A schema is compiled into a model, which can then be used to create, read, update, and delete documents in a MongoDB collection.
Note:
Multiple models can be created from a single schema, each representing a different MongoDB collection.
Schema is defined once and used repeatedly, while a model can be instantiated multiple times to work with different documents in the collection.
Check this code:
import mongoose from "mongoose";
// Define a schema for a user document
const userSchema = new mongoose.Schema({
firstName: {
type: String,
required: true
},
lastName: {
type: String,
required: true
},
email: {
type: String,
required: true,
unique: true
},
age: {
type: Number,
required: false,
default: null,
min: 18
}
});
// Create a model for the user collection based on the user schema
const User = mongoose.model('User', userSchema);
// Use the User model to create and save a new user document
const newUser = new User({
firstName: 'John',
lastName: 'Doe',
email: '[email protected]',
age: 25
});
newUser.save()
.then(doc => console.log(doc))
.catch(err => console.error(err));