Mongoose is a popular Object Data Modeling (ODM) library for Node.js and MongoDB. It provides a straight-forward, schema-based solution to model your application data and provides a number of powerful features to help you interact with your data in MongoDB.
You can install Mongoose using npm:
npm install mongoose
To use Mongoose in your Node.js application, you first need to import it:
import mongoose from "mongoose"
Next, you need to connect to your MongoDB database:
mongoose.connect("mongodb+srv://USERNAME:PASSWORD@USERNAME-cluster.qbfd8ay.mongodb.net/DB_NAME");
Now you can define your data model using a schema:
const userSchema = new mongoose.Schema({
name: String,
age: Number,
email: String,
password: String
});
Once you have defined your schema, you can create a model for it:
const User = mongoose.model('User', userSchema);
Now you can use the model to interact with your data in MongoDB:
const user = new User({
name: 'John Doe',
age: 28,
email: 'john.doe@example.com',
password: 'password123'
});
user.save((err, user) => {
if (err) throw err;
console.log('User saved successfully!');
});
Mongoose provides a number of powerful features to help you interact with your data in MongoDB:
- Schema-based data modeling
- Built-in type casting
- Validation of data before saving to the database
- Query building and execution
- Middleware support (pre and post hooks)
- Plugins support
- Virtual properties
- Transactions
- Aggregation