skip to Main Content

I am trying to make my registration page work. When I type a username and password, I just get {"message":"Registration failed"}. I’m getting the following error:

MongooseError: Operation `users.findOne()` buffering timed out after 10000ms
    at Timeout.<anonymous> (C:pathtoyourfilenode_modulesmongooselibdriversnode-mongodb-nativecollection.js:186:23)
    at listOnTimeout (node:internal/timers:569:17)
    at process.processTimers (node:internal/timers:512:7)

This is my server.js code for the user registration form:

app.post('/user/register', async (req, res) => {
  const { username, password } = req.body;

  try {
    const existingUser = await User.findOne({ username });

    if (existingUser) {
      return res.status(409).json({ message: 'Username already exists' });
    }

    // Create a new user instance
    const newUser = new User({ username, password });

    // Save the user to the database
    await newUser.save();

    console.log('User registered successfully');
    res.status(200).json({ message: 'User registered successfully' });
  } catch (err) {
    console.error(err); // Log the error for debugging
    res.status(500).json({ message: 'Registration failed' });
  }
});

Hello, I am trying to make my registration page work. When I type a username and password, I just get {"message":"Registration failed"}. I’m getting the following error: and now i also get,

MongooseError: Operation `users.findOne()` buffering timed out after 10000ms
    at Timeout.<anonymous> (C:UsersRistovskiWINDesktopMladenWebnode_modulesmongooselibdriversnode-mongodb-nativecollection.js:186:23)        
    at listOnTimeout (node:internal/timers:569:17)
    at process.processTimers (node:internal/timers:512:7)

2

Answers


  1. Chosen as BEST ANSWER

    Okay this worked, now its ok, i created the first username and it went fine, but now when i try to create another username i get " Username already exist" even that its not the same username and password... also i get this error Mongoose: users.findOne({ username: undefined }, {}) this is when i submit the new username and password


  2. // Dot env
    import dotenv from 'dotenv';
    dotenv.config();
    
    // Mongoose Connection
    import mongoose from 'mongoose';
    mongoose.connect(process.env.MONGO_URI, {
      useNewUrlParser: true,
      useUnifiedTopology: true,
      useCreateIndex: true,
      useFindAndModify: false,
    });
    
    //creating main platform
    const connectDB = require('./config/db');
    connectDB(); // Call the function here
    console.log(mongoose.connection.readyState);
    
    app.post('/user/register', async (req, res) => {
      const { username, password } = req.body;
    
      try {
        const existingUser = await User.findOne({ username });
    
        if (existingUser) {
          return res.status(409).json({ message: 'Username already exists' });
        }
    
        // Create a new user instance
        const newUser = new User({ username, password });
    
        // Save the user to the database
        await newUser.save();
    
        console.log('User registered successfully');
        res.status(200).json({ message: 'User registered successfully' });
      } catch (err) {
        console.error(err); // Log the error for debugging
        res.status(500).json({ message: 'Registration failed' });
      }
    });
    

    Let me explain each fix I made:

    • I added the dotenv module to load environment variables from a .env file. This way, you can store your MongoDB connection string securely and avoid exposing it in your code. You need to install dotenv as a dependency and create a .env file in your root directory with the following content:
    MONGO_URI=<your connection string>
    
    • I imported mongoose and used it to connect to your MongoDB database using the MONGO_URI variable. I also passed some options to avoid deprecation warnings and enable some features. You can read more about them [here].
    • I moved the connectDB function call to the top of your server.js file, before using any Mongoose models. This ensures that you establish a connection to your database before performing any queries. The connectDB function is defined in your config/db file and it simply wraps the mongoose.connect() call in a try-catch block.
    • I added a console.log statement to print the mongoose.connection.readyState property. This is a number that indicates the status of the connection: 0 for disconnected, 1 for connected, 2 for connecting, and 3 for disconnecting. You can use this to debug your connection issues.
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search