I am looking to store data collected from an HTML form into a MongoDB database. Below is the code I am using:
<!DOCTYPE html>
<html>
<head>
<title>Getting Started with Node and MongoDB</title>
</head>
<body>
<h1>Getting Started with Node and MongoDB</h1>
<form method="post" action="/addname">
<label>Enter Your Name</label><br>
<input type="text" name="firstName" placeholder="Enter first name..." required>
<input type="text" name="lastName" placeholder="Enter last name..." required>
<input type="submit" value="Add Name">
</form>
</body>
</html>
Additionally, here is my JavaScript code in app.js:
var express = require("express");
var app = express();
var port = 3000;
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
var mongoose = require("mongoose");
var promise = mongoose.connect('mongodb://localhost:27017/node-demo', {
useMongoClient: true,
});
var nameSchema = new mongoose.Schema({
firstName: String,
lastName: String
});
var User = mongoose.model("User", nameSchema);
app.use("/", (req, res) => {
res.sendFile(__dirname + "/index.html");
});
app.post("/addname", (req, res) => {
var myData = new User(req.body);
myData.save()
.then(item => {
res.send("item saved to database");
})
.catch(err => {
res.status(400).send("unable to save to database");
});
});
app.listen(port, () => {
console.log("Server listening on port " + port);
});
It seems that the POST request is functioning correctly, but even after entering data and submitting the form, the database remains empty. Can anyone help me understand why the information is not being saved?