'authentification is not comparing values

ok, i have a mongodb server inside it i have a database called userdbs for storing the users that signup using my http://localhost:8085/add-user ,after registration it redirect the user to the login page which have the following address http://localhost:8085/login ,the registration process works fine, but when it comes to authentification i got an error, for exemple i have in the dabase a user with an email : "[email protected]" password:"password" when i try to do the the authentification i get the following error:

{"message":"E11000 duplicate key error collection: myFirstDatabase.userdbs index: email_1 dup key: { email: "[email protected]" }"}

here is the code in the controller.js:

var Userdb = require('../model/model');
const bcrypt = require('bcrypt');

// create and save new user
exports.create = async(req,res)=>{
    // validate request
    if(!req.body){
        res.status(400).send({ message : "Content can not be emtpy!"});
        return;
    }
    
    
    
    // new user
    const user = new Userdb({
        name : req.body.name,
        username : req.body.username,
        email : req.body.email,
        password : req.body.password
    })
    

    


    // save user in the database
    user
        .save(user)
        .then(data => {
            //res.send(data)
            res.redirect('/login');
        })
        .catch(err =>{
            res.status(500).send({
                message : err.message || "Some error occurred while creating a create operation"
            });
        });


 
}


//searching for user and doing comparaison
exports.login = async(req, res) => {

    const user = Userdb.find(user => user.email = req.body.email);
        if(user == null)
        {
            return res.status(400).send('cannot find user');
        }
    
        try 
        {
            if(req.body.password == user.password)
                res.send("Success")
            else
                res.send("username/password incorrect")
        }
        catch
        {
            res.status(500).send();
        }
    
}

here is the api routes in the router.js:

const express = require('express');
const route = express.Router()

const services = require('../services/render');
const controller = require('../controller/controller');

/**
 *  @description Root Route
 *  @method GET /
 */
route.get('/', services.homeRoutes);

/**
 *  @description add users
 *  @method GET /add-user
 */
route.get('/add-user', services.add_user)

/**
 *  @description login users
 *  @method POST /login
 */
route.get('/login', services.login)


/**
 *  @description for update user
 *  @method GET /update-user
 */
route.get('/update-user', services.update_user)


// API
route.post('/api/users', controller.create);
route.get('/api/users', controller.find);
route.put('/api/users/:id', controller.update);
route.delete('/api/users/:id', controller.delete);


module.exports = route

and here its the render.js:

const axios = require('axios');


exports.homeRoutes = (req, res) => {
    // Make a get request to /api/users
    axios.get('http://localhost:8085/api/users')
        .then(function(response){
            res.render('index', { users : response.data });
        })
        .catch(err =>{
            res.send(err);
        })

    
}

exports.add_user = (req, res) =>{
    res.render('add_user');
}

exports.login = (req, res) =>
{
    res.render('login');
}

exports.update_user = (req, res) =>{
    axios.get('http://localhost:_085/api/users', { params : { id : req.query.id }})
        .then(function(userdata){
            res.render("update_user", { user : userdata.data})
        })
        .catch(err =>{
            res.send(err);
        })
}

the model.js

const mongoose = require('mongoose');

var schema = new mongoose.Schema({
    name : {
        type : String,
        required: false
    },
    
    username : {
        type: String,
        required: false,
        unique: true
    },
    
    email : {
        type: String,
        requird: true,
        unique: true
    },
    
    password : {
        type: String,
        required: true
}


})

const Userdb = mongoose.model('userdb', schema);

module.exports = Userdb;

mongoose connection.js

const mongoose = require('mongoose');

const connectDB = async () => {
    try{
        // mongodb connection string
        const con = await mongoose.connect(process.env.MONGO_URI, {
            useNewUrlParser: true,
            useUnifiedTopology: true,
            useFindAndModify: false,
            useCreateIndex: true
        })

        console.log(`MongoDB connected : ${con.connection.host}`);
    }catch(err){
        console.log(err);
        process.exit(1);
    }
}

module.exports = connectDB

here is the server.js if its needed:

const express = require('express');
const dotenv = require('dotenv');
const morgan = require('morgan');
const bodyparser = require("body-parser");
const path = require('path');
const bcrypt = require('bcrypt');

const connectDB = require('./server/database/connection');

const app = express();

dotenv.config( { path : 'config.env'} )
const PORT = process.env.PORT || 8085

// log requests
app.use(morgan('tiny'));

// mongodb connection
connectDB();

// parse request to body-parser
app.use(bodyparser.urlencoded({ extended : true}))

// set view engine
app.set("view engine", "ejs")
//app.set("views", path.resolve(__dirname, "views/ejs"))

// load assets
app.use('/assets', express.static(path.resolve(__dirname, "assets")))


// load routers
app.use('/', require('./server/routes/router'))

app.listen(PORT, ()=> { console.log(`Server is running on http://localhost:${PORT}`)});

also forget to mention both views login.ejs and add-user.ejs have the same for action

<form action="/api/users" method="POST">

I appreciate your consideration/guidance/help/time



Solution 1:[1]

Check the URL for login on client side. Maybe the client calls add-user instead of login.

Moreover, the route for login is missing, you should add it to router.js file:

route.post('/login', controller.login)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 user14967413