Home > Enterprise >  Username undefined even though schema and model were already defined
Username undefined even though schema and model were already defined

Time:11-19

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": "[email protected]"
}

CodePudding user response:

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