nodejs를 사용하여 mongodb에 데이터 저장

Sep 22 2020

저는 스스로 학습하는 nodeJS입니다. 이제 MongoDB에 데이터를 삽입하려고 시도했습니다.

여기에 값을 삽입하고 제출 버튼을 클릭하면 데이터가 mongodb에 성공적으로 저장되고 성공적인 메시지가 반환됩니다.

하지만 이것은 오류입니다

TypeError: Cannot read property 'location' of undefined

다음은 코드 조각입니다.

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

답변

3 PascalLamers Sep 22 2020 at 16:27

body-parserExpress와 함께 미들웨어를 사용해보십시오 .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 }));

이렇게하면 양식의 데이터가 요청 body( req.body.location)에 포함되어야합니다.

elemetrics Sep 22 2020 at 16:31

요청 본문이 정의되지 않은 것 같습니다. 이는 express가 요청 본문을 올바르게 구문 분석하지 않기 때문일 수 있습니다. 해결책은 아마도 본문 파서를 사용하는 것입니다.

npm install --save body-parser

그런 다음 body-parser를 파일로 가져옵니다.

const bodyParser = require('body-parser')

그런 다음 "/ new"핸들러 앞에 다음 줄을 배치합니다.

app.use(bodyParser)