nodejs kullanarak mongodb'a veri kaydetme

Sep 22 2020

Ben kendi kendine öğrenen nodeJS'im, Şimdi MongoDB'ye veri eklemeyi denedim ve bu benim amacım

Buraya değerler giriniz ve gönder butonu tıklandığında, verileri başarılı bir şekilde mongodb'a kaydetmeli ve bu başarılı bir mesaj döndürmelidir.

Ama bu hata

TypeError: Cannot read property 'location' of undefined

İşte kod parçacıkları

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'));

Yanıtlar

3 PascalLamers Sep 22 2020 at 16:27

body-parserEkspres ile birlikte ara yazılımı kullanmayı deneyin :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 }));

Bu şekilde formdaki veriler isteğe body( req.body.location) dahil edilmelidir.

elemetrics Sep 22 2020 at 16:31

Görünüşe göre isteğin gövdesi tanımlanmamış. Bunun nedeni, express'in istek gövdesini doğru şekilde ayrıştırmaması olabilir. Çözüm muhtemelen bir vücut ayrıştırıcı kullanmaktır.

npm install --save body-parser

Ardından gövde ayrıştırıcısını dosyanıza aktarın:

const bodyParser = require('body-parser')

Ardından bu satırı "/ yeni" işleyicinin önüne yerleştirin:

app.use(bodyParser)