Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Hello, i am trying to complete user registration form that uses (HTML,CSS,JS,NODE.JS,PASSPORT.JS

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:\path\to\your\file\node_modules\mongoose\lib\drivers\node-mongodb-native\collection.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,

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

MongooseError: Operation `users.findOne()` buffering timed out after 10000ms
    at Timeout.<anonymous> (C:\Users\RistovskiWIN\Desktop\MladenWeb\node_modules\mongoose\lib\drivers\node-mongodb-native\collection.js:186:23)        
    at listOnTimeout (node:internal/timers:569:17)
    at process.processTimers (node:internal/timers:512:7)

>Solution :

// 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.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading