Operation buffering timed out after 10000ms even DB is connected - node.js

I can't find what I'm doing wrong. I already dug through a plethora of stacksoverflows but didn't find any solution.
I constantly getting MongooseError: Operation `users.insertOne()` buffering timed out after 10000ms whenever I try to register a user. Some solutions say that I didn't connect to DATABASE. However, I get a confirm that the DB is connected successfully.
Here is the codes.
server.js
const express = require("express");
const mongoose = require("mongoose");
const cors = require("cors");
const app = express();
const PORT = process.env.PORT || 5000;
// Init Middleware
app.use(express.json({ extended: false }));
app.use(cors());
// Bodyparser
app.use(express.urlencoded({ extended: false }));
// Connecting to mongoose
mongoose.connect(
process.env.REACT_APP_MONGO_URI,
{
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
useFindAndModify: false,
},
() => {
console.log("Connected successfully to DB!");
// Listening for actions
app.listen(PORT, () => console.log(`Server started on port ${PORT}`));
}
);
// Defined Routes
app.use("/", require("./routes/index"));
app.use("/users", require("./routes/users"));
users.js
const router = express.Router();
const bcrypt = require("bcryptjs");
const User = require("../models/User");
router.get("/login", (req, res) => {
res.send("Login");
});
router.get("/register", (req, res) => {
res.send("Register");
});
// #route POST /register
// #desc Creates a user
// #access Public
router.post("/register", async (req, res) => {
try {
const { name, surname, email, password, repeatedPassword } = req.body;
if (!name || !surname || !email || !password || !repeatedPassword) {
return res.status(400).json({ msg: "Not all fields were filled." });
}
if (password !== repeatedPassword) {
return res.status(400).json({ msg: "Password doesn't match." });
}
if (password.length < 6) {
return res
.status(400)
.json({ msg: "Password should be at least 6 characters long." });
}
/*
const user = await User.findOne({ email: email });
if (user) {
return res
.status(400)
.json({ msg: "This email is already specified by another user." });
}
*/
const newUser = new User({
name,
surname,
email,
password,
});
newUser.save();
console.log(newUser);
res.json(newUser);
} catch (error) {
res.status(500).send("Server error");
}
});
module.exports = router;
User.js (model)
const Schema = mongoose.Schema;
const UserSchema = new Schema({
name: {
type: String,
required: true,
},
surname: {
type: String,
required: true,
},
email: {
type: String,
required: true,
},
password: {
type: String,
required: true,
},
date: {
type: Date,
default: Date.now,
},
});
module.exports = User = mongoose.model("User", UserSchema);

include user model and create one.
const User = require('./User')
await User.create({ name, surname, email, password, })

Related

Node JS dealing with error "Cannot Post /"

I am trying to send a post request and dealing with this error "Cannot POST /". What can be the problem? I am using a Postman to send a Post request to our server. My post request is
localhost:4000
Here is my index.js code:
const Joi = require('joi');
Joi.objectId = require('joi-objectid')(Joi);
const mongoose = require('mongoose');
const users = require('./routes/users');
const express = require('express');
const app = express();
mongoose.connect('mongodb://localhost/mongo-games')
.then(() => console.log('Now connected to MongoDB!'))
.catch(err => console.error('Something went wrong', err));
app.use(express.json());
app.use('/api/users', users);
const port = process.env.PORT || 4000;
app.listen(port, () => console.log(`Listening on port ${port}...`));
And here is my user.js code:
const Joi = require('joi');
const mongoose = require('mongoose'); //needed for validation & creating user mongodb schema
const User = mongoose.model('User', new mongoose.Schema({
name: {
type: String,
required: true,
minlength: 5,
maxlength: 50
},
email: {
type: String,
required: true,
minlength: 5,
maxlength: 255,
unique: true
},
password: {
type: String,
required: true,
minlength: 5,
maxlength: 1024
}
}));
function validateUser(user) {
const schema = {
name: Joi.string().min(5).max(50).required(),
email: Joi.string().min(5).max(255).required().email(),
password: Joi.string().min(5).max(255).required()
};
return Joi.validate(user, schema);
}
exports.User = User;
exports.validate = validateUser;
And my users.js code:
const { User, validate } = require('../models/user');
const express = require('express');
const router = express.Router();
router.post('/', async (req, res) => {
// First Validate The Request
const { error } = validate(req.body);
if (error) {
return res.status(400).send(error.details[0].message);
}
// Check if this user already exisits
let user = await User.findOne({ email: req.body.email });
if (user) {
return res.status(400).send('That user already exisits!');
} else {
// Insert the new user if they do not exist yet
user = new User({
name: req.body.name,
email: req.body.email,
password: req.body.password
});
await user.save();
res.send(user);
}
});
module.exports = router;
What am I missing here? Any ideas?
Your middleware is- app.use('/api/users', users);
and your post is about that route.
In your postman> URL > you need to write localhost:4000/api/users.
because this is the URL that gets to the router.
Make sure that you are sending request to the /api/users. Looks like you are trying to send it to / which you are not handling.

How to compare login data on NodeJS with the registered users in MongoDB

I just need to know how to compare email/password in MongoDB whenever a user login tries to log in. If the user enters wrong crediantals it should give an Invalid pass/email
I just want an idea of how to compare values. Your little time can save my day
function login() {
app.post('/login/', async(req, res) => {
const query = new Model({
email: req.body.email,
password: req.body.password
});
});
}
//here's the Schema and Mongoose Connection
mongoose.connect("mongodb://localhost:27017/Login", { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log('connected mfs'))
.catch((err) => console.error("error found...", err));
const LoginSchema = new mongoose.Schema({
email: { type: String, required: true },
password: { type: String, required: true }
});
//connection
const port = process.env.port || 3000;
app.listen(port, () => console.log(`listening to port ${port}`));
//here's the headers
const express = require('express');
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extend: true }));
const mongoose = require('mongoose')
First import bcrypt.
and do the below code in your login function
import bcrypt from 'bcryptjs';
let user = await model.findOneUser({ email: this.req.body.email});
if (user == null) {
return sendResponse(this.res, 400, FAILED_MSG, 'Incorrect id or password.');
}
let isValidPassword = await bcrypt.compare(this.req.body.password, user.password);
if (!isValidPassword) {
return sendResponse(this.res, 400, FAILED_MSG, 'Incorrect id or password.');
}
// do success code

OverwriteModelError: Cannot overwrite `user` model once compiled

I am facing this issue. I looked online for hours to find out what the problem is before posting here. I keep getting this error OverwriteModelError: Cannot overwrite ``user`` model once compiled. after sending a post request via postman and I can't find out what's going on. could you help me find out what's going on? thank you so much in advance!
server.js
const express = require("express");
const app = express();
const user = require("./routes/user");
const connectDB = require("./config/db");
connectDB();
app.use(express.json({extended: false}));
app.get("/", (req, res) => {
res.send("welcome to our api");
});
app.use("/user", user);
const PORT = 3000 || process.env.PORT;
app.listen(PORT, () => {
console.log(`PORT ${PORT} listening and refeshing...`);
});
db.js
const mongoose = require("mongoose");
const connectDB = () =>
mongoose
.connect(
"some database",
{
useNewUrlParser: true,
useUnifiedTopology: true,
}
)
.then(
() => {
console.log("mongoDB conneted");
},
(err) => {
console.log(err);
}
);
module.exports = connectDB;
user.js
const express = require("express");
const router = express.Router();
const mongoose = require("mongoose");
const bcrypt = require("bcrypt");
const jwt = require("jsonwebtoken");
const {body, validationResult} = require("express-validator");
router.get("/", (req, res) => {
res.send("hello");
});
router.post(
"/",
[
// password must be at least 5 chars long
body("email").isEmail(),
body("password").not().isEmpty(),
],
async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty) {
return res.status(400).json({errors: errors.array()});
}
try {
const UsersSchema = mongoose.Schema({
email: {type: String, required: true},
password: {type: String, required: true},
});
var users = mongoose.model("user", UsersSchema);
var user = new users({
email: req.body.email,
password: req.body.password,
});
const salt = await bcrypt.genSalt(10);
user.password = await bcrypt.hash(req.body.password, salt);
user.save((err, user1) => {
if (err) {
console.log("error posing user");
throw err;
}
});
console.log(user.id);
const payload = {
user: {
id: user.id,
},
};
} catch (error) {
console.log(error);
res.status(400);
}
}
);
module.exports = router;
Every time the route runs it tries to create a schema which is already created.Mongoose create the collection with the first argument user by converting it to plural i.e. users.

Node.JS : Async/Await taking so long and never ending

I'm trying to set up an API with MongoDB (Mongoose) with a JWT authentication. I am at the first step where I create an user in the DB.
But I encounter a problem : the async/await taking so long and never ending, while the user is not created on DB. I don't know why.
I'm testing with POSTMAN for requests. For information, when I'm starting my app, I'm getting the "connected to db !" who appear correctly.
Can someone help me please ?
app.js
'use strict';
const express = require("express"),
app = express(),
authRoutes = require('./routes/auth'),
externalRoutes = require('./routes/web'),
database = require('./database/db'),
bodyParser = require("body-parser"),
mongoose = require('mongoose')
;
require('dotenv').config();
var options = { useNewUrlParser: true, useUnifiedTopology: true };
mongoose.connect("mongodb+srv://user:password#host.mongodb.net/test?retryWrites=true&w=majority", options, () => console.log('connect to db !'));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use('/api/user', authRoutes);
app.use('/', externalRoutes);
app.listen(8080);
auth.js
const router = require('express').Router();
const User = require('../database/schemas/User');
router.post('/register', async (req, res) => {
const user = new User({
name: req.body.name,
email: req.body.email,
password: req.body.password,
});
const savedUser = await user.save((error, userDoc) => {
if (error) return res.status(400).send(error);
});
res.send({
user: savedUser._id
});
}).post('/login', (req, res) => {
});
module.exports = router;
User.js
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
name: {
type: String,
required: true,
min: 6,
max: 255
},
email: {
type: String,
required: true,
max: 255,
min: 10
},
password: {
type: String,
required: true,
max: 1024
},
createdAt: {
type: Date,
default: Date.now()
},
updatedAt: {
type: Date,
default: Date.now()
},
});
module.exports = mongoose.model('User', userSchema);
In Auth.js do this instead
const router = require('express').Router();
const User = require('../database/schemas/User');
router.post('/register', async (req, res) => {
const user = new User({
name: req.body.name,
email: req.body.email,
password: req.body.password,
});
try {
// if you are using await, don't pass it a callback
const savedUser = await user.save();
return res.send({
user: savedUser._id
});
} catch (error) {
// use try/catch to handle error instead of error first parameter in callback
return res.status(400).send(error);
}
}).post('/login', (req, res) => {
});
module.exports = router;
Here is a link to the documentation that shows you how to correctly use the save method. https://mongoosejs.com/docs/api.html#model_Model-save

POST Request not working - MongDB and Express JS using Mongoose

I started working on a MERN App and am trying to write a restful api. Code is working fine. But POST Requests are not working.
moviemodel.js
const mongoose = require('mongoose')
const Schema = mongoose.Schema
const Movie = new Schema(
{
name: { type: String, required: true },
time: { type: [String], required: true },
rating: { type: Number, required: true },
},
{ timestamps: true },
)
module.exports = mongoose.model('users', Movie)
moviectrl.js
const Movie = require('../models/moviemodel')
createMovie = (req, res) => {
const body = req.body
if (!body) {
return res.status(400).json({
success: false,
error: 'You must provide a movie',
})
}
const movie = new Movie(body)
if (!movie) {
return res.status(400).json({ success: false, error: err })
}
movie
.save()
.then(() => {
return res.status(201).json({
success: true,
id: movie._id,
message: 'Movie created!',
})
})
.catch(error => {
return res.status(400).json({
error,
message: 'Movie not created!',
})
})
}
index.js
const express = require('express')
const bodyParser = require('body-parser')
const cors = require('cors')
var MongoClient = require('mongodb').MongoClient;
const movieRouter = require('./routes/movierouter')
const app = express()
const apiPort = 3000
app.use(bodyParser.urlencoded({ extended: true }))
app.use(cors())
app.use(bodyParser.json())
MongoClient.connect('mongodb://127.0.0.1:27017/cinema', { useNewUrlParser:
true }, function(err, client) {
const db = client.db('cinema')
if(err) throw err;
console.log('Successfully connected')
})
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.use('/api', movieRouter)
app.listen(apiPort, () => console.log(`Server running on port
${apiPort}`))
movierouter.js
const express = require('express')
const MovieCtrl = require('../controllers/moviectrl')
const router = express.Router()
router.post('/movie', MovieCtrl.createMovie)
router.put('/movie/:id', MovieCtrl.updateMovie)
router.delete('/movie/:id', MovieCtrl.deleteMovie)
router.get('/movie/:id', MovieCtrl.getMovieById)
router.get('/movies', MovieCtrl.getMovies)
module.exports = router
When I send a POST Request using the link localhost:3000/api/movie and send a JSON Data through Postman. There is no response.
https://imgur.com/a/l6GvDbu
I've tested your app and found that your database is hanging ...
Replace your database connection with this 😃:
const url = 'mongodb://localhost:27017/cinema';
mongoose.connect(url, {
useUnifiedTopology: true,
useNewUrlParser: true,
useCreateIndex: true,
useFindAndModify: false
}, console.log(`DB running on ${url}`));
https://imgur.com/gallery/q4Y0lW2
exports.createMovie = async(req,res){
try{
const create = await ModelName.create(req.body)
if(ceate){
res.send("created")
}else{
res.send("error")
}
}catch(err){
res.send(err)
}
}

Resources