简体   繁体   中英

Inserting data to MongoDB with expressJS

I'm trying to post some data to a collection in MongoDB . Very basic. I'm new to both mongo and express and ran into some problems. Here are my code so far:

<form action="/post" method="post">

    <label for="first_name">First Name</label>
    <input type="text" id="first_name" name="first_name">

    <button type="submit">Submit</button>
</form>


const express = require('express');
const expressApp = express();

const MongoClient = require('mongodb').MongoClient;

const url = 'mongodb://localhost:27017/agile-app-db';

const dbName = 'agile-app-db';


//Post data
expressApp.post('/post' , function (request, response) {

    let member = {
        first_name: request.body.first_name
    };

    MongoClient.connect(url, function (error, db) {
        if (error) throw error;
        let databaseobject = db.db(dbName);
        databaseobject.collection('Members').insertOne(member, function (error, result) {
            if (error) throw error;
            console.log("Member inserted");
            db.close();
        });
    });

    response.redirect('/agileApp');

});

I'm running into the following error: TypeError: Cannot read property 'first_name' of undefined

Try using the body-parser middleware

const bodyParser = require('body-parser')

app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())

You need to add middleware to your express app that parses the query string. Try adding expressApp.use(express.urlencoded({ extended: false })) before any routes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM