MongooseError - Operation `users.findOne()` buffering timed out after 10000ms
Full error message
My code was working before initially but I don't know why it just stopped working and gave me this error:
MongooseError: Operation `users.findOne()` buffering timed out after 10000ms
at Timeout.<anonymous> (/Users/nishant/Desktop/Yourfolio/backend/node_modules/mongoose/lib/drivers/node-mongodb-native/collection.js:184:20)
at listOnTimeout (internal/timers.js:549:17)
at processTimers (internal/timers.js:492:7)
I am trying to authenticate the user by login with JWT. My client runs fine but in my backend I get this error. My backend code:
import neuron from '@yummyweb/neuronjs'
import bodyParser from 'body-parser'
import cors from 'cors'
import mongoose from 'mongoose'
import emailValidator from 'email-validator'
import passwordValidator from 'password-validator'
import User from './models/User.js'
import Portfolio from './models/Portfolio.js'
import bcrypt from 'bcryptjs'
import jwt from 'jsonwebtoken'
import auth from './utils/auth.js'
// Dot env
import dotenv from 'dotenv'
dotenv.config()
// Custom Password Specifications
// Username Schema
const usernameSchema = new passwordValidator()
usernameSchema.is().min(3).is().max(18).is().not().spaces()
// Password Schema
const passwordSchema = new passwordValidator()
passwordSchema.is().min(8).is().max(100).has().uppercase().has().lowercase().has().digits().is().not().spaces()
const PORT = process.env.PORT || 5000
const neuronjs = neuron()
// Middleware
neuronjs.use(bodyParser())
neuronjs.use(cors())
// Mongoose Connection
mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true }, () => console.log("MongoDB Connected"))
// API Routes
neuronjs.POST('/api/auth/signup', async (req, res) => {
const { username, email, password, passwordConfirmation } = req.body
// Validation: all fields are filled
if (!username || !email || !password || !passwordConfirmation) {
return res.status(400).json({
"error": "true",
"for": "fields",
"msg": "fill all the fields"
})
}
// Validation: username is valid
if (usernameSchema.validate(username, { list: true }).length !== 0) {
return res.status(400).json({
"error": "true",
"for": "username",
"method_fail": usernameSchema.validate(username, { list: true }),
"msg": "username is invalid"
})
}
// Validation: email is valid
if (!emailValidator.validate(email)) {
return res.status(400).json({
"error": "true",
"for": "email",
"msg": "email is invalid"
})
}
// Validation: password is valid
if (passwordSchema.validate(password, { list: true }).length !== 0) {
return res.status(400).json({
"error": "true",
"for": "password",
"method_fail": passwordSchema.validate(password, { list: true }),
"msg": "password is invalid"
})
}
// Validation: password is confirmed
if (password !== passwordConfirmation) {
return res.status(400).json({
"error": "true",
"for": "confirmation",
"msg": "confirmation password needs to match password"
})
}
// Check for existing user with email
const existingUserWithEmail = await User.findOne({ email })
if (existingUserWithEmail)
return res.status(400).json({ "error": "true", "msg": "a user already exists with this email" })
// Check for existing user with username
const existingUserWithUsername = await User.findOne({ username })
if (existingUserWithUsername)
return res.status(400).json({ "error": "true", "msg": "a user already exists with this username" })
// Generating salt
const salt = bcrypt.genSalt()
.then(salt => {
// Hashing password with bcrypt
const hashedPassword = bcrypt.hash(password, salt)
.then(hash => {
const newUser = new User({
username,
email,
password: hash
})
// Saving the user
newUser.save()
.then(savedUser => {
const newPortfolio = new Portfolio({
user: savedUser._id,
description: "",
socialMediaHandles: {
github: savedUser.username,
dribbble: savedUser.username,
twitter: savedUser.username,
devto: savedUser.username,
linkedin: savedUser.username,
}
})
// Save the portfolio
newPortfolio.save()
// Return the status code and the json
return res.status(200).json({
savedUser
})
})
.catch(err => console.log(err))
})
.catch(err => console.log(err))
})
.catch(err => console.log(err))
})
neuronjs.POST('/api/auth/login', async (req, res) => {
try {
const { username, password } = req.body
// Validate
if (!username || !password) {
return res.status(400).json({ "error": "true", "msg": "fill all the fields", "for": "fields", })
}
const user = await User.findOne({ username })
if (!user) {
return res.status(400).json({ "error": "true", "msg": "no account is registered with this username", "for": "username" })
}
// Compare hashed password with plain text password
const match = await bcrypt.compare(password, user.password)
if (!match) {
return res.status(400).json({ "error": "true", "msg": "invalid credentials", "for": "password" })
}
// Create JWT token
const token = jwt.sign({ id: user._id }, process.env.JWT_SECRET)
return res.json({ token, user: { "id": user._id, "username": user.username, "emaiSolutionsource: stackoverflow \u2197
In my experience this happens when your database is not connected, Try checking out following things - Is you database connected and you are pointing to the same url from your code. check if your mongoose.connect(...) code is loading. I faced this issue where I was running the node index.js from my terminal and mongoose connect code was into different file. After requiring that mongoose code in index.js it was working again.
API access
Get this solution programmatically \u2014 free, no authentication.
curl https://depscope.dev/api/error/a51de72e1f7ba421f027c879859a79958d0c4168de2b93e6cc58f9078d120a40hash \u00b7 a51de72e1f7ba421f027c879859a79958d0c4168de2b93e6cc58f9078d120a40