menyimpan data ke mongodb menggunakan nodejs
Saya belajar sendiri nodeJS, Sekarang saya mencoba memasukkan data di MongoDB dan ini tujuan saya
masukkan nilai di sini dan setelah tombol kirim diklik, seharusnya data berhasil disimpan ke mongodb dan ini akan mengembalikan pesan yang berhasil.
Tapi ini kesalahannya
TypeError: Cannot read property 'location' of undefined
Berikut cuplikan kodenya
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'));
Jawaban
Coba gunakan body-parsermiddleware bersama dengan 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 }));
Dengan cara ini data dari formulir harus disertakan dalam request body( req.body.location)
Tampaknya isi permintaan tidak ditentukan. Ini mungkin karena express tidak mengurai isi permintaan dengan benar. Solusinya mungkin menggunakan body parser.
npm install --save body-parser
Kemudian impor body-parser ke dalam file Anda:
const bodyParser = require('body-parser')
Kemudian letakkan baris ini sebelum penangan "/ baru":
app.use(bodyParser)