2

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

1

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you Gabriel. It was my missing middleware that cost the error.
1

Try using the body-parser middleware

const bodyParser = require('body-parser')

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.