SIDMISH
SIDMISH

Reputation: 166

Node JS | TypeError: Cannot read property 'first_name' of undefined

Im just starting out with MEAN application, and im stuck while adding data into the database. So please help me to find the solution for this.

This is the root file, entry point in the application

//Importing  modules
var express=require('express');
var mongoose=require('mongoose');
var bodyparser=require('body-parser');
var cors=require('cors');
var path=require('path');

var app=express();
const route=require('./routes/route');

//Connect to mongoDb
mongoose.connect('mongodb://localhost:27017/contactlist');

//on connection
mongoose.connection.on('connected',()=>{
    console.log("Successfully established a connection to mongodb Database ")
});

//on error
mongoose.connection.on('error',(err)=>{
    if(err){
        console.log("Failed to established a connection "+err);
    }
});
const port=3000;
//For routing
app.use('/api',route);

//Adding middleware -cors
app.use(cors());

//body-parser
app.use(bodyparser.json());

//Static Files
app.use(express.static(path.join(__dirname,'public')));

//port no


app.get('/',(req,res)=>{
    res.send('Foobar');
});

app.listen(port,()=>{
    console.log("Server started listening to port "+port);  
})

And this my route file,

const express = require('express');
const router = express.Router();
// fetching the schema
const Contact = require('../Models/contacts');
//Retriving the contacts
router.get('/contacts', (req,res,next)=>{
    Contact.find(function(err,contacts){
        // Sending to client in json format
        res.json(contacts); 
    });
});

// Adding Contacts
router.post('/contact', (req,res,next)=>{
    let newContact = new Contact({
        first_name : req.body.first_name,
        last_name : req.body.last_name,
        phone : req.body.phone
    });

    newContact.save((err,contact)=>{
        if(err){
            res.json({msg: "Failed to add contact."});
        }else{
            res.json({msg:"Contact added sucessfully"});
        }
    });
});

//Deleteing contact
router.delete('/contact/id',(req,res,next)=>{
    Contact.remove({_id:req.params.id},function(err,result){
        if(err){
            res.json(err);
        }else{
            res.json(result);
        }
    })  
});

module.exports=router;

Now, I'm trying to add a few records in DB (Mongo DB) using postman, but it's throwing an error saying "TypeError: Cannot read property 'first_name' of undefined, at router.post (C:\Mean App\ContactList\routes\route.js:16:25)"

In postman, for header, I'm using "Content-type: application/json" and in raw body, I'm adding JSON data like this,

{
    "first_name" : "Siddhesh",
    "last_name" : "Mishra",
    "phone" : "9594106324"
}

And here is my code where I'm creating schema

const mongoose=require('mongoose');
const ContactSchema = mongoose.Schema({
    first_name:{
        type:String,
        required:true
    },
    last_name:{
        type:String,
        required:true
    },
    phone:{
        type:String,
        required:true
    }
});

const Contact=module.exports=mongoose.model('Contact',ContactSchema);

thank you.

Upvotes: 1

Views: 2592

Answers (2)

Stamos
Stamos

Reputation: 3998

You will have to move body-parser above the routes use and should work

//body-parser
app.use(bodyparser.json());

//For routing
app.use('/api',route);

From Express API v4.x

app.use([path,] callback [, callback...])

...

Middleware functions are executed sequentially, therefore the order of middleware inclusion is important.

Upvotes: 5

codejockie
codejockie

Reputation: 10844

body-parser needs to go before the routes:

//Importing  modules
var express = require('express');
var mongoose = require('mongoose');
var bodyparser = require('body-parser');
var cors = require('cors');
var path = require('path');

var app = express();
const route = require('./routes/route');

//Connect to mongoDb
mongoose.connect('mongodb://localhost:27017/contactlist');

//on connection
mongoose.connection.on('connected', () => {
  console.log("Successfully established a connection to mongodb Database ")
});

//on error
mongoose.connection.on('error', (err) => {
  if (err) {
    console.log("Failed to established a connection " + err);
  }
});

const port = 3000;

//body-parser
app.use(bodyparser.json()); // here


//Adding middleware -cors
app.use(cors());

//Static Files
app.use(express.static(path.join(__dirname, 'public')));

// For routing
app.use('/api', route);

app.get('/', (req, res) => {
  res.send('Foobar');
});

app.listen(port, () => {
  console.log("Server started listening to port " + port);
})

To always be on the safe side your routes should always come last after all middleware.

Upvotes: 0

Related Questions