Omar Diaa
Omar Diaa

Reputation: 286

Adding data to MongoDB using node JS and I get this error: "TypeError: Cannot read property 'username' of undefined"

I am trying to add to mongo DB some data using a POST request sent from postman application. I have successfully created the database and a message was printed indicating that. Below is my code:

users.js file:

const router = require("express").Router();
let User = require("../models/user.model"); //the model we created

router.route("/").get((req, res) => {
  //If the link(route) is routes/users/ and it is a get request this is what is going to happen

  //
  User.find() //find: gets all what is in the database
    .then((users) => res.json(users)) //this puts in users all the users values
    .catch((err) => res.status(400).json("Error: " + err));
});

router.route("/add").post((req, res) => {
  //this handles the post requests at routes/users/add
  res.setHeader("Content-Type", "application/json");
  const username = req.body.username; //Gets the username passed

  const newUser = new User({ username }); //creates a new User (User model imported from the other file)

  newUser
    .save() //save: saves the created user in the database
    .then(() => res.json("user added!")) //
    .catch((err) => res.status(400).json("Error: " + err));
});

module.exports = router;

user.model.js:

const { Schema } = require("mongoose");

const mongoose = require("mongoose");
const schema = mongoose.Schema;

const userSchema = new schema(
  {
    username: {
      type: String,
      required: true,
      unique: true,
      trim: true,
      minlength: 3,
    },
  },
  {
    timestamps: true,
  }
);
const User = mongoose.model("User", userSchema); //"User" is the name we are going to use
//userSchema is the name of the schema

module.exports = User;

server.js:

const cors = require("cors");

const mongoose = require("mongoose");

const uri =
  "mongodb+srv://user:[email protected]/user?retryWrites=true&w=majority";

mongoose.connect(uri, {
  useNewUrlParser: true,
  useCreateIndex: true,
  useUnifiedTopology: true,
});

const connection = mongoose.connection;
connection.once("open", () => {
  console.log("DB Established!");
});

require("dotenv").config();
const app = express();
const port = process.env.PORT || 5000;
// app.use(cors);

const exerciesesRouter = require("./routes/exercises");
const usersRouter = require("./routes/users");

app.use("/exercises", exerciesesRouter); //if any one goes to /exercise it will load everything inside exerciseRouter
app.use("/users", usersRouter);

app.listen(port, () => {
  console.log(`Server is running on port: ${port}`);
});

app.get("/", (req, res) => {
  res.send("hello");
  res.end("ehee");
});

Now, using Postman, I send a POST request to the link: "http://localhost:5000/users/add" and I get a message saying:

TypeError: Cannot read property 'username' of undefined
    at router.route.post (F:\code\MERN2\backend\routes\users.js:16:29)
    at Layer.handle [as handle_request] (F:\code\MERN2\backend\node_modules\express\lib\router\layer.js:95:5)
    at next (F:\code\MERN2\backend\node_modules\express\lib\router\route.js:137:13)
    at Route.dispatch (F:\code\MERN2\backend\node_modules\express\lib\router\route.js:112:3)
    at Layer.handle [as handle_request] (F:\code\MERN2\backend\node_modules\express\lib\router\layer.js:95:5)
    at F:\code\MERN2\backend\node_modules\express\lib\router\index.js:281:22
    at Function.process_params (F:\code\MERN2\backend\node_modules\express\lib\router\index.js:335:12)
    at next (F:\code\MERN2\backend\node_modules\express\lib\router\index.js:275:10)
    at Function.handle (F:\code\MERN2\backend\node_modules\express\lib\router\index.js:174:3)
    at router (F:\code\MERN2\backend\node_modules\express\lib\router\index.js:47:12)
    at Layer.handle [as handle_request] (F:\code\MERN2\backend\node_modules\express\lib\router\layer.js:95:5)
    at trim_prefix (F:\code\MERN2\backend\node_modules\express\lib\router\index.js:317:13)
    at F:\code\MERN2\backend\node_modules\express\lib\router\index.js:284:7
    at Function.process_params (F:\code\MERN2\backend\node_modules\express\lib\router\index.js:335:12)
    at next (F:\code\MERN2\backend\node_modules\express\lib\router\index.js:275:10)
    at expressInit (F:\code\MERN2\backend\node_modules\express\lib\middleware\init.js:40:5)

I searched for the questions and tried all the suggested answers (which are too few) and none worked for me.

Upvotes: 1

Views: 116

Answers (1)

kedar sedai
kedar sedai

Reputation: 1722

Basically, in NodeJs and Express Middleware functions have access to req, res object and next function in the req-res cycle Middleware. The task of the middleware functions are

  • Execute any code
  • End req res cycle and also make changes to req res cycle

You need to have body-parser middleware. It parses the incoming request bodies in a middleware before your handlers.

//Middlewares for bodyParser
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());

More on bodyParser middleware bodyParser.

Upvotes: 1

Related Questions