Using Schemas and Models in Mongoose
Let’s illustrate the concepts of schemas and models with a simple example of a user management system:
const mongoose = require('mongoose');
// Define User Schema
const userSchema = new mongoose.Schema({
username: { type: String, required: true },
email: { type: String, required: true, unique: true },
age: { type: Number, min: 18, max: 100 }
});
// Create User Model
const User = mongoose.model('User', userSchema);
// Create a new user document
const newUser = new User({
username: 'john_doe',
email: 'john@example.com',
age: 25
});
// Save the user document to the database
newUser.save()
.then(user => console.log('User created:', user))
.catch(err => console.error('Error creating user:', err));
In this example:
- We define a user schema with fields for username, email, and age, along with validation rules.
- We create a User model using the schema.
- We create a new user document using the model and save it to the database.
Why does Mongose have Both Schemas and Models
In the world of MongoDB and Node.js, Mongoose is a popular object modeling tool that provides a straightforward way to interact with MongoDB databases. One of the key features of Mongoose is its use of schemas and models, which help define the structure of documents and provide an abstraction layer for performing database operations.
In this article, we’ll delve into why Mongoose has both schemas and models, exploring their roles, differences, and how they work together, with examples and outputs to illustrate each concept clearly.