How to use Mongoose in controller to validate login form with user model in express

To use Mongoose in a controller to validate a login form with a user model in an Express.js application, you'll need to perform the following steps:

Step 1: Create a User Model with Mongoose.

First, create a user model using Mongoose to interact with your MongoDB database. This model should define the structure of the user document, and you can use it to perform database operations like finding users by their email and password. Here's a basic example:

// models/User.js
const mongoose = require('mongoose');

const userSchema = new mongoose.Schema({
  email: { type: String, required: true, unique: true },
  password: { type: String, required: true },

const User = mongoose.model('User', userSchema);

module.exports = User;

Step 2: Create a Login Route in Express.

Create a route in your Express application that handles user login. This route should receive the user's email and password from the login form, validate them, and authenticate the user. Here's a basic example:

// controllers/authController.js
const express = require('express');
const User = require('../models/User');
const router = express.Router();'/login', async (req, res) => {
  const { email, password } = req.body;

  try {
    // Find the user by email
    const user = await User.findOne({ email });

    if (!user) {
      return res.status(404).json({ message: 'User not found' });

    // Validate the password
    if (password !== user.password) {
      return res.status(401).json({ message: 'Incorrect password' });

    // Authentication successful
    res.json({ message: 'Login successful' });
  } catch (error) {
    res.status(500).json({ message: 'Server error' });

module.exports = router;

Step 3: Handle Login Form Submission.

In your frontend code, when the user submits the login form, send a POST request to the /login route with the user's email and password. For example, using HTML and Fetch API:

<!-- login.html -->
<form id="login-form">
  <input type="email" name="email" placeholder="Email" required>
  <input type="password" name="password" placeholder="Password" required>
  <button type="submit">Login</button>

  document.getElementById('login-form').addEventListener('submit', async (e) => {

    const formData = new FormData(;

    try {
      const response = await fetch('/login', {
        method: 'POST',
        body: formData,

      if (response.ok) {
        // Redirect or display a success message
        console.log('Login successful');
      } else {
        // Handle error response
        const data = await response.json();
    } catch (error) {
      console.error('Network error:', error);

Step 4: Connect the Controller and Routes.

Finally, connect the authController to your Express application by requiring it in your main app file (e.g., app.js) and using app.use() to define the routes:

// app.js
const express = require('express');
const mongoose = require('mongoose');
const authController = require('./controllers/authController');

const app = express();

// Middleware and configuration setup

// Connect to MongoDB
mongoose.connect('mongodb://localhost/mydb', {
  useNewUrlParser: true,
  useUnifiedTopology: true,

// Use the authController for authentication routes
app.use('/auth', authController);

// Start the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);

Now, when a user submits the login form, it sends a POST request to the /login route, where the controller handles the login validation using Mongoose and responds accordingly. Make sure to adapt this example to your specific authentication requirements and security considerations.

Muhammad Alfaiz
Alfaiz 6 months ago
Notify of
Inline Feedbacks
View all comments
Would love your thoughts, please comment.x