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
Let me know if I need to create an env file or make changes in index.js
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:
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