Storing Data into the Database using Mongoose Model ๐๐พ
Once your React.js application is connected to MongoDB, the next big step is learning
how to actually save data. This is where Mongoose โ the most popular
Object Data Modeling (ODM) library for MongoDB and React.js โ comes in. Mongoose lets
you define a Schema, compile it into a Model, and use that Model to
create, validate, and store documents in your database with clean, readable code.
In this tutorial, we will learn:
save() and create()What is Mongoose?
Mongoose is an Object Data Modeling (ODM) library that sits between your React.js application and MongoDB. Instead of writing raw MongoDB queries, Mongoose lets you define a clear structure (Schema) for your data, enforce validation rules, and interact with the database using simple, readable JavaScript methods. This makes your code more organized, predictable, and easier to maintain โ especially as your application grows.
---Step 1: Install Mongoose
Before we can define a Schema or Model, we need to install Mongoose in our project.
npm install mongoose
Step 2: Connect to MongoDB
Create a file called db.js to handle the database connection using
mongoose.connect().
const mongoose = require("mongoose");
const connectToMongo = () => {
mongoose
.connect("mongodb://127.0.0.1:27017/myAppDB")
.then(() => console.log("Connected to MongoDB successfully"))
.catch((err) => console.error("MongoDB connection error:", err));
};
module.exports = connectToMongo;
Step 3: Define a Mongoose Schema
A Schema defines the shape of the documents inside a MongoDB collection โ
field names, data types, default values, and validation rules. Let's create a
User.js model file inside a models folder.
const mongoose = require("mongoose");
const { Schema } = mongoose;
const UserSchema = new Schema({
name: {
type: String,
required: true,
},
email: {
type: String,
required: true,
unique: true,
},
password: {
type: String,
required: true,
},
createdAt: {
type: Date,
default: Date.now,
},
});
Step 4: Compile the Schema into a Model
A Model is a wrapper built from a Schema โ it's what actually lets us create,
read, update, and delete documents in the corresponding MongoDB collection. We compile
our Schema using mongoose.model() and export it for use across our app.
const User = mongoose.model("User", UserSchema);
module.exports = User;
Step 5: Save Data Using the Model
Now that our User Model is ready, we can use it to store data in two common ways โ
creating a new document instance and calling save(), or using the shorthand
create() method.
const User = require("./models/User");
// Method 1: new instance + save()
const createUserWithSave = async () => {
const newUser = new User({
name: "Rahul Sharma",
email: "rahul@example.com",
password: "securePass123",
});
const savedUser = await newUser.save();
console.log("User saved:", savedUser);
};
// Method 2: create() shorthand
const createUserWithCreate = async () => {
const savedUser = await User.create({
name: "Priya Verma",
email: "priya@example.com",
password: "anotherPass456",
});
console.log("User created:", savedUser);
};
Step 6: Store Data via an Express Route
In a real application, data usually comes from a client request (like a signup form). Here's how we save that data to MongoDB inside an Express route, with proper error handling.
const express = require("express");
const router = express.Router();
const User = require("../models/User");
router.post("/api/signup", async (req, res) => {
try {
const { name, email, password } = req.body;
const newUser = await User.create({ name, email, password });
res.status(201).json({
success: true,
message: "User stored successfully",
data: newUser,
});
} catch (error) {
res.status(500).json({
success: false,
message: "Error storing user",
error: error.message,
});
}
});
module.exports = router;
save() vs create(): Which One to Use?
| Method | How It Works | Best Used When |
|---|---|---|
new Model() + save() |
Creates a document instance first, then saves it โ gives access to instance methods before saving | You need to modify or validate the document before saving |
Model.create() |
Creates and saves the document in a single step | You just want a quick, direct way to insert data |
Features and Learnings:-
mongoose.model().save() and create() methods.