Reputation: 399
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
Upvotes: 2
Views: 339
Reputation: 1447
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.
Upvotes: 1
Reputation: 2204
Try using the body-parser middleware
const bodyParser = require('body-parser')
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
Upvotes: 1