lưu dữ liệu vào mongodb bằng nodejs

Sep 22 2020

Tôi đang tự học nodeJS, Bây giờ tôi đã cố gắng chèn dữ liệu vào MongoDB và đây là mục tiêu của tôi

chèn các giá trị vào đây và sau khi nhấn nút gửi, sẽ lưu dữ liệu thành công vào mongodb và điều này sẽ trả về một thông báo thành công.

Nhưng đây là lỗi

TypeError: Cannot read property 'location' of undefined

Đây là các đoạn mã

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

Trả lời

3 PascalLamers Sep 22 2020 at 16:27

Hãy thử sử dụng body-parserphần mềm trung gian cùng với 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 }));

Bằng cách này, dữ liệu từ biểu mẫu sẽ được đưa vào request body( req.body.location)

elemetrics Sep 22 2020 at 16:31

Có vẻ như nội dung của yêu cầu là không xác định. Điều này có thể là do express không phân tích cú pháp chính xác nội dung yêu cầu. Giải pháp có lẽ là sử dụng trình phân tích cú pháp cơ thể.

npm install --save body-parser

Sau đó nhập body-parser vào tệp của bạn:

const bodyParser = require('body-parser')

Sau đó, đặt dòng này trước trình xử lý "/ new":

app.use(bodyParser)