Username undefined even though schema and model were already defined - node.js

Please help review my error. I have defined my user schema but it is still undefined. I have spent hours on this error but I cannot seem to find where did I go wrong.
Here's my schema and model:
const { model, Schema } = require("mongoose");
const userSchema = new Schema({
username:String,
employeeId: String,
accessLevel: String,
role: String,
company: String,
password: String,
email: String,
createdAt: Date,
});
module.exports = model("User", userSchema);
Here's controller:
const User = require("../models/user");
const registerUser = (req, res, next) => {
let user = new User({
username: req.body.username,
employeeId: req.body.employeeId,
accessLevel: req.body.accessLevel,
role: req.body.role,
company: req.body.company,
password: req.body.password,
email: req.body.email,
createdAt: new Date(),
});
module.exports = {
registerUser
};
Here's connection to DB and server:
const express = require("express");
const mongoose = require("mongoose");
const { MONGODB } = require("./config");
const userRoute = require("./routes/userRouter");
const PORT = process.env.PORT || 4000;
mongoose
.connect(MONGODB, { useNewUrlParser: true, useUnifiedTopology: true })
.then(console.log("Database connected"))
.catch((err) => {
console.log(err);
});
const server = express();
server.use((err, req, res, next) => {
console.error(err);
res.status(err.statusCode).json(err);
});
server.use("/api/user", userRoute);
server.use(express.urlencoded({ extended: true }));
server.use(express.json());
server.listen(PORT, () => console.log(`Server is listening on ${PORT}`));
Here's router:
const express = require("express");
const usersControllers = require("../controllers/usersControllers");
const router = express.Router();
router.post("/registeruser", usersControllers.registerUser);
module.exports = router;
Post request on Postman: http://localhost:4000/api/user/registeruser
body:
{
"username": "Susan",
"employeeId": "12345",
"accessLevel": "Account Admin",
"role": "MC - Engineer",
"company": "Mello",
"password": "Choochootrain",
"email": "susan#hotmail.com"
}

Try to change the order of your middleware declarations:
const server = express();
server.use(express.urlencoded({ extended: true }));
server.use(express.json());
server.use("/api/user", userRoute);
server.use((err, req, res, next) => {
console.error(err);
res.status(err.statusCode).json(err);
});

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.

TypeError: Cannot read property 'username' of undefined in node.JS / express cannot post to route

I keep getting a type Error when posting to my exercises. here is my exercises route:
const router = require("express").Router();
let Exercise = require("../models/exercise.model.js");
//get all exercises
router.get("/", (req, res) => {
Exercise.find()
.then(exercises => res.json(exercises))
.catch(err => res.status(400).json("error: " + err));
});
//add an exercise
router.route("/add").post((res, req) => {
//parse req.body
const username = req.body.username;
const description = req.body.description;
const duration = Number(req.body.duration);
const date = Date.parse(req.body.date);
//create new exercise object
const newExercise = new Exercise({
username,
description,
duration,
date
});
//save newExercise object
newExercise
.save()
.then(() => res.json("Exercise Added!"))
.catch(err => res.status(400).json("error: " + err));
});
module.exports = router;
and here is my model:
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
// create exercise data model
const exerciseSchema = new Schema(
{
username: {
type: String,
required: true
},
description: {
type: String,
required: true
},
duration: {
type: Number,
required: true
},
date: {
type: Date,
required: true
}
},
{
timestamps: true
}
);
const Exercise = mongoose.model("Exercise", exerciseSchema);
module.exports = Exercise;
I've tried to change the route to router.post instead of router.route, I've tried changing the data model.
as well as my server.js:
const express = require("express");
const mongoose = require("mongoose");
const app = express();
const cors = require("cors");
//middleware
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
require("dotenv").config();
//environment
const port = process.env.PORT || 5000;
//mongoose establish connection
const uri = process.env.ATLAS_URI;
mongoose.connect(uri, {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true
});
const connection = mongoose.connection;
connection.once("open", () => {
console.log("MongoDB connection established successfully");
});
//routers for users and exercises
const exercisesRouter = require("./routes/exercises");
const usersRouter = require("./routes/users");
app.use("/exercises", exercisesRouter);
app.use("/users", usersRouter);
//error log
app.use(function (err, req, res, next) {
console.error(err.stack);
res.status(500).send(`error: ${err}`).next();
});
app.listen(port, () => {
console.log(`server is up and running on port: ${port}`);
});
Here is the error logged in Insomnia:
Any Help is greatly appreciated!
You are misplace req and res in router.route("/add").post((res, req) => {.
Fix it: router.route("/add").post((req, res) => {

SyntaxError: Unexpected token b in JSON at position 3

i am new to MERN framework
try to use postman to test my get and post request. but keep getting this error SyntaxError: Unexpected token b in JSON at position 3
here is my schema -------------------------
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const UserSchema = new Schema({
firstname: {
type: String,
required: true
},
lastname: {
type: String,
required: true
},
sex: {
type: String,
required: true
},
age: {
type: Number,
required: true
},
password: {
type: String,
required: true
},
admin: {
type: Boolean,
default: true
}
});
module.exports = User = mongoose.model("user", UserSchema);
here is my route---------------------
const express = require("express");
const router = express.Router();
const User = require("../../models/user");
router.get("/", (req, res) => {
User.find()
.sort({ age: -1 })
.then(users => res.json(users));
});
router.post("/", (req, res) => {
const newUser = new User({
firstname: req.body.firstname
});
newUser.save().then(user => res.json(user));
});
module.exports = router;
here is my server------------------
const express = require("express");
const mongoose = require("mongoose");
const users = require("./routes/api/users");
const app = express();
app.use(express.json());
const db = require("./config/keys").mongoURI;
mongoose
.connect(db, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log("MongoDB Connected"))
.catch(err => console.log(err));
app.use("/api/users", users);
const port = 5000;
app.listen(port, () => console.log(`server started on port ${port}`));
please help!! stuck for whole day
You do not need express.json() for GET routes. So please try moving app.use(express.json()); to route file before POST request.
Also if you are using express version >= 4, please use app.use(bodyParser.json()) from body-parser package.

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

Resources