skip to Main Content

I’m trying to check if a user is in my mongodb database but I keep getting an error: Operation users.findOne() buffering timed out after 10000ms. I’ve tried many things but i cant seem to get it to work. Please help.

server.js

const express = require('express');
const app = express();
const dotenv = require('dotenv').config();
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const path = require('path');
const cookieParser = require("cookie-parser");

const indexRoute = require('./routes/index');
const authRoute = require('./routes/auth');

mongoose.connect(process.env.DB_CONNECT, { useNewUrlParser: true }, () => {
    console.log('Connected to MongoDB');
});

app.use(express.json());
app.use(cookieParser());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static(__dirname + '/views'));
app.use(express.static('Public'));
app.set('view engine', 'ejs');
app.set("views", path.join(__dirname, "views"));
app.disable('x-powered-by');

app.use('/', indexRoute);
app.use('/auth', authRoute);
app.get('/login', (req, res) => {
    res.render('login/index.ejs', {
        loginError: req.cookies['loginError'],
    });
});

app.listen(3000, () => console.log('Server Up and running'));

auth.js

const express = require('express');
const router = express.Router();
const jwt = require('jsonwebtoken');
const User = require('../models/User');
const bcrypt = require("bcryptjs");
const { loginValidation } = require('../validation');

router.post('/login', async(req, res) => {
    //Validate Data
    const { error } = loginValidation(req.body);

    if (error) {
        let msg = error.message.replace(/["]/g, '')[0].toUpperCase() + error.message.replace(/["]/g, '').slice(1) + '!';
        return res.cookie('loginError', msg, [{ httpOnly: true }]).redirect('/login');;

    }
    const user = await User.findOne({ email: req.body.email });
    if (!user) {
        let msg = 'Invalid email or password!'
        return res.cookie('loginError', msg, [{ httpOnly: true }]).redirect('/login');;
    }


    const validPass = await bcrypt.compare(req.body.password, user.password);
    if (!validPass) {
        let msg = 'Invalid email or password!'
        return res.cookie('loginError', msg, [{ httpOnly: true }]).redirect('/login');;
    }
    const token = jwt.sign({ _id: user._id }, process.env.TOKEN_SECRET);
    res.header('auth-token', token).redirect('/dashboard');
});

module.exports = router;

.env

DB_CONNECT = not putting the url for security but this is where i have my mongodb connection url

Sorry if this is a dumb question. Any help is appreciated.

2

Answers


  1. I THINK you are not properly awaiting for the db connection. Try refactoring this

    mongoose.connect(process.env.DB_CONNECT, { useNewUrlParser: true }, () => {
    console.log(‘Connected to MongoDB’);
    });

    Into this

    const connectDatabase = async () => {
      try {
        mongoose.set("useNewUrlParser", true);
        
        await mongoose.connect(process.env.DB_CONNECT);
    
        console.log("connected to database");
      } catch (error) {
        console.log(error);
        process.exit(1);
      }
    };
    
    connectDatabase();
    

    Also, are you hosting your db locally? I would try that too, Atlas sometimes gives trouble.

    Asides from that, I don’t really know, sorry, hope it helps.

    Login or Signup to reply.
  2. Try using FIND instead of findOne

    user.find({email: req.body.email })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search