I am currently studying with Udemy but could not get an answer through their forums. I’m creating my own site to try and better understand mongoDB using mongoose, express, EJS. The site has multiple forms. When submitting form data with a post request I am attempting to insert a single record into a database but instead get 4 duplicate records inserted. When using console.log to check the object being sent it also appears 4 times, however I have tried to send it only once.
Here is my app.js code:
“`
const express = require(“express”);
const bodyParser = require(“body-parser”);
const ejs = require(“ejs”);
const mongoose = require(“mongoose”);
const app = express();
app.use(bodyParser.urlencoded({extended: true}));
app.set(‘view engine’, ‘ejs’);
app.use(express.static(“public”));
// Connect / Create to the Database
mongoose.connect(“mongodb://localhost:27017/stationDB”, { useNewUrlParser: true, useUnifiedTopology: true });
// Create a new Schema
const stnSchema = new mongoose.Schema ({
name: String
});
const contactSchema = new mongoose.Schema ({
name: String,
email: String,
message: String
});
// Create a new Model
const Station = mongoose.model(“Station”, stnSchema);
const Message = mongoose.model(“Message”, contactSchema);
//Creating an array of items to populate the database
const item1 = {
name: “item 1”
};
const item2 = {
name: “item 2”
};
const item3 = {
name: “item 3”
};
const item4 = {
name: “item 4”
};
const stationData = [item1, item2, item3, item4];
//Check the database to see if items have already been inserted, if not then insert the initial items
Station.find({}, function(err, results) {
if (err) {
console.log(err);
}
else {
if (results.length === 0) {
Station.insertMany(stationData), function(err) {
if (err) {
console.log(err);
}
else {
console.log(“No records found – adding initial records”)
}
}
}
else {
console.log(“Records already in place – none added”)
}
}
});
//Routes
// Get Requests
app.get(“/”, function(req, res) {
Station.find({}, function(err, results) {
if (err) {
console.log(“Error: cannot find records for stationList”);
}
else {
const stationList = results;
res.render(“index”, {stationItems: stationList});
}
})
});
// Post Requests
app.post(“/ticketSales”, function(req, res) {
const formSubmit = req.body;
const adultCost = parseFloat(formSubmit.adults) * 7.85;
const childCost = parseFloat(formSubmit.child) * 3.50;
const totalCost = adultCost + childCost;
console.log(totalCost);
res.render(“ticketSales”, {
adults: formSubmit.adults,
adultCost: adultCost,
children: formSubmit.child,
childCost: childCost,
ticketTotal: totalCost,
})
});
app.post(“/contact”, function(req, res) {
const formName = req.body.name;
const formEmail = req.body.email;
const formMsg = req.body.message;
const message = new Message({
name: formName,
email: formEmail,
message: formMsg
});
console.log(message);
message.save();
res.render(“contact”);
});
// App Listen
app.listen(3000, function() {
console.log(‘Server started, port 3000’); //
});
HTML:
“`
<form name=”contact-form” action=”/contact” method=”post”>
<label for=”contact-name”>Name</label>
<input id=”contact-name” name=”name” type=”text”>
<label for=”email”>Email</label>
<input id=”email” name=”email” type=”text”>
<label for=”contact-msg”>Message</label>
<textarea name=”message” id=”contact-msg”>
</textarea>
<button type=”submit” value=”contact” name=”contactBtn”>Submit</button>
</form>
I’m still very new to this and learning but any help would be much appreciated. The only progress I have made is to note that the initial records which are used to populate a drop down in a form do not duplicate when inserted / retrieved but the records sent via post requests are effected. I believe it is related to the post request. Additionally I have found changing the form submit button from to reduces the number of submissions from 4 to 2 – could the html form be the culprit?