Table of Contents
For this series, I'm following an excellent video tutorial from Traversy Media
Introduction
In this tutorial, we'll walk you through the process of creating a user model for a Todos application using the Mongoose library. The user model will serve as the foundation for managing user-related data, such as registration, authentication, and user-specific tasks.
Create user model
To begin, we'll create a user model by defining a schema for the user data. This schema will include fields for the user's name
, email
, and password
. Notably, we'll set the email field as unique to ensure the integrity of user data.
const mongoose = require('mongoose');
const userSchema = mongoose.Schema(
{
name: {
type: String,
required: [true, 'Please add a name'],
},
email: {
type: String,
required: [true, 'Please add an email'],
unique: true,
},
password: {
type: String,
required: [true, 'Please add a password'],
},
},
{
timestamps: true,
}
);
module.exports = mongoose.model('User', userSchema);
By setting timestamps to true, Mongoose will automatically create a createdAt
and updatedAt
fields in user collection.
Add user to todo model
Next, we'll establish a connection between the user and todo models by adding a user
field to the todoModel.js
.
user: {
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: 'User',
},
Here I'm specifying the user field with ObjectId
and referencing it to the User
model.
Create user controller
Now, I am creating a userController.js
file in the controllers
folder and adding a function for registering a user, authenticating/logging a user, and getting the logged-in user data.
const registerUser = (req, res) => {
res.json({ message: "Register User" });
};
const loginUser = (req, res) => {
res.json({ message: "Login User" });
};
const getLoggedInUser = (req, res) => {
res.json({ message: "Logged In User data" });
};
module.exports = {
registerUser,
loginUser,
getLoggedInUser,
};
Currently, I am just displaying a message. We'll later add the actual functionality to it.
Create user routes
To expose these controller functions through API endpoints, we'll create a userRoutes.js
file and define routes for user registration, login, and retrieval of user data.
const express = require("express");
const router = express.Router();
const {
registerUser,
loginUser,
getLoggedInUser,
} = require("../controllers/userController");
router.post("/", registerUser);
router.post("/login", loginUser);
router.get("/me", getLoggedInUser);
module.exports = router;
and add it to the server.js
file.
...
app.use('/api/goals', require('./routes/goalRoutes'));
app.use('/api/users', require('./routes/userRoutes')); //added user route
...
Now run the server go to the postman and check your routes. It will give a result like this.
- Register User
- Login User
- Get LoggedIn User
Connect with me