skip to Main Content

I was creating a movie website and I was setting up a login I tried to register using POST through Insomnia which resulted in an error saying "MongooseError: Operation users.findOne() buffering timed out after 10000ms". I tried to solve as much as possible but so far not able to fix this issue. Can anyone help me fix the issue?

import userModel from "../model/userModel.js";

export default class AuthController{
  static async sendToken(user, statusCode, res){
    const token = user.getSignedToken(res);
    res.status(statusCode).json({
        success: true,
        token,
    });
  }

  static async registerController(req, res, next) {
    try {
      const { username, email, password } = req.body;
      const exisitingEmail = await userModel.findOne({ email });
      if (exisitingEmail) {
        return next(new errorResponse("Email is already register", 500));
      }
      const user = await userModel.create({ username, email, password });
      this.sendToken(user, 201, res);
    } catch (error) {
      console.log(error);
      next(error);
    }
  }

  static async loginController(req, res, next){
    try {
      const { username, password } = req.body;
      if (!username || !password) {
        return next(new errorResponse("Please provide email or password"));
      }
      const user = await userModel.findOne({ username });
      if (!user) {
        return next(new errorResponse("Invalid Creditial", 401));
      }
      const isMatch = await user.matchPassword(password);
      if (!isMatch) {
        return next(new errorResponse("Invalid Creditial", 401));
      }
      this.sendToken(user, 200, res);
    } catch (error) {
      console.log(error);
      next(error);
    }
  }

  static async logoutController(req, res, ){
    res.clearCookie('refreshToken');
    return res.status(200).json({
        success:true,
        message:'Logout Successfully',
    });
  }
}

2

Answers


  1. Chosen as BEST ANSWER

    import app from './server.js'
    import mongodb from 'mongodb'
    import reviewsDAO from './dao/reviewsDAO.js'
    
    const MongoClient = mongodb.MongoClient
    const mongo_username = process.env['MONGO_USERNAME']
    const mongo_password = process.env['MONGO_PASSWORD']
    const uri = `mongodb+srv://${mongo_username}:${mongo_password}@cluster0.as4w6t7.mongodb.net/?retryWrites=true&w=majority`
    
    const port = 8000
    
    MongoClient.connect(
      uri,
      {
        maxPoolSize: 50,
        wtimeoutMS: 2500,
        useNewUrlParser: true
      }
    )
      .catch(err => {
        console.error(err.stack)
        process.exit(1)
      })
      .then(async client => {
        await reviewsDAO.injectDB(client)
        app.listen(port, () => {
          console.log(`listening on port ${port}`)
        })
      })

    Let me know if I need to create an env file or make changes in index.js


  2. Usually this error indicates, that the database connection was not established by the time you use your model.

    documentat

    You need to do the following:

    • make sure that mongo database is up and running
    • You establish connection to database with mongoose.connect with valid connection string, i.e: mongoose.connect('mongodb://127.0.0.1:27017')

    related question

    I assume you’re using express.js for your website (based on tags you provide with the question). You can organize your code in such a way that the express application starts only after the connection to mongo is successfully established.

    somewhere in index.js

    const express = require('express')
    const mongoose = require('mongoose')
    
    async function main() {
      const {PORT, DB_CONNECTION_STRING} = process.env;    
      try {
        await mongoose.connect(DB_CONNECTION_STRING, {
           // other connection options
        });
    
        // setup your express app and run it
        const app = express()
    
        app.listen(PORT, () => {
          console.log(`server started`);
        });
      } catch (err) {
        console.error(err);
        throw err;
      }
    };
    
    main();
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search