In this section, we will learn how to structure user data using Mongoose by creating a model and schema. This will allow us to interact with MongoDB in a clean and consistent way.
✅ Step 1: Create a models
Folder
Inside your src
directory, create a folder named models
. This folder will contain all your database models.
project-root/ └── src/ └── models/ └── User.ts
✅ Step 2: Define the User Schema and Model
Now, inside User.ts
, define the schema and export the model:
// src/models/User.ts import * as mongoose from ‘mongoose’; const userSchema = new mongoose.Schema({ email: { type: String, required: true }, password: { type: String, required: true } }); export default mongoose.model(‘users’, userSchema);
✔️ Note: Mongoose will automatically create a collection named
users
if it doesn’t already exist.
✅ Step 3: Using the Model in a Controller
In your UserController
, you can now use this model to save users to the database.
// src/controllers/UserController.ts import User from ‘../models/User’; export class UserController { static login(req, res, next) { const { email, password } = req.body; const user = new User({ email, password }); user.save() .then((savedUser) => { res.status(201).json(savedUser); }) .catch((err) => { // Proper error handling const error = new Error(err.message || ‘User creation failed’); next(error); }); } }
⚠️ You can also directly call
next(err)
without wrapping if you prefer.
✅ Step 4: Test with Postman
Now, let’s test it by sending a POST request to /api/user/login
using Postman.
Request:
POST /api/user/login Content-Type: application/json { “email”: “[email protected]”, “password”: “testPassword” }
Response:
{ “_id”: “6845623a65a6916b81f51336”, “email”: “[email protected]”, “password”: “testPassword”, “__v”: 0 }
✅ MongoDB automatically generated _id
and __v
fields.
✅ Step 5: Verify in MongoDB
-
Login to MongoDB Atlas.
-
Navigate to your Cluster > Collections.
-
Open the
users
collection. -
You will see the newly added document.
🎉 Even if the collection didn’t exist before, Mongoose creates it automatically when the first document is inserted.
✅ Summary
-
We created a Mongoose schema and model for users.
-
Used the model to save user data in MongoDB.
-
Handled database errors cleanly with
try/catch
orpromise.catch
. -
Verified successful insertion via Postman and MongoDB Atlas.