1

I am self learning nodeJS, Now I tried to insert data in MongoDB and this my goal

insert values in here and once submit button is clicked, should save the data successfully to mongodb and this should return a successful message.

enter image description here

But this is the error

TypeError: Cannot read property 'location' of undefined

Here are the code snippets

const express = require('express');
const dotenv = require("dotenv").config();
const address = process.argv[2];
const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const app = express();

//INSERT TO MONGO DB
//connect to mongo db
mongoose.connect('mongodb://localhost/weathertest2');
mongoose.Promise = global.Promise;


//create weather schema
const WeatherSchema = new Schema({
    location:{
        type: String
    },
    temperature:{
        type: String
    },
    observationTime:{
        type: String
    }

});

const Weather = mongoose.model('weather', WeatherSchema);

// post request
app.post('/new', function(req, res){
    new Weather({
        location    : req.body.location,
        temperature: req.body.temperature,
        observationTime   : req.body.observationTime                
    }).save(function(err, doc){
        if(err) res.json(err);
        else    res.send('Successfully inserted!');
    });
});
 

// listen for request
app.listen(process.env.port || 9000, function(){
    console.log('now listening for  testing request');
});
app.use(express.static('public'));

2 Answers 2

3

Try using the body-parser middleware alongside with express: https://www.npmjs.com/package/body-parser

const bodyParser = require("body-parser");

/* 
* Parses the text as URL encoded data (which is how browsers tend to send
* form data from regular forms set to POST) and
* exposes the resulting object (containing the keys and values) on req.body
*/

app.use(bodyParser.urlencoded({ extended: true }));

This way the data from the form should be included in the request body (req.body.location)

Sign up to request clarification or add additional context in comments.

4 Comments

Glad I could help @rickyProgrammer !
i wanna ask, how can i return the input value in the temperature for example?
Please create another question for this ! Thanks !
0

It seems that the body of the request is undefined. This might be because express isn't parsing the request body correctly. The solution is probably to use a body parser.

npm install --save body-parser

Then import body-parser into your file:

const bodyParser = require('body-parser')

Then place this line before the "/new" handler:

app.use(bodyParser)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.