Is it possible to store data from a form directly into a MongoDB database?

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?

Answer №1

After testing your code, I noticed that the app.post function was not being executed. This issue arises because you are utilizing app.use to serve the index.html file. In Express.js, app.use is primarily used for applying middleware to your application. For serving static files like HTML, you should use app.get instead. This method instructs Express to catch requests to the root path (/) and execute the specified function.

app.get("/", (req, res) => {
 res.sendFile(__dirname + "/index.html");
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Conceal and reveal elements using v-if

Check out my fiddle: DEMO creating a new Vue instance: { el: '#app', data: { modules: ['abc', 'def'] } } I am looking for a way to hide or show elements using v-if based on the values in an array called modules[]. ...

JQuery Form Validation - Detecting Input Changes

Currently, I have a form set up with jQuery validation that works well, but I want to enhance its functionality. The form uses a plugin for validation, but it only checks for errors upon submission. I'm interested in finding a way to validate the fiel ...

What is the best way to determine which option is most suitable: types, classes, or function types in TypeScript for

Currently, I am developing a small todo command line utility with a straightforward program structure. The main file is responsible for parsing the command line arguments and executing actions such as adding or deleting tasks based on the input provided. E ...

How to Fix Items Being Pushed Down by 'Particleground' Jquery Plugin Due to Z-Index and Positioning

I'm grappling with understanding z-index and positioning, despite reading various questions and articles on the topic. Currently, I'm attempting to incorporate a Jquery Plugin called 'Particleground': https://github.com/jnicol/particle ...

Incorporating a .json file into res.render to pass data

Is there a way to pass an object array similar to the one below into res.render? var DataArray = [ {"type": "c#", "script":"csharp script"}, {"type": "javascript", "script":"javascr ...

Avoiding data type conversion in JavaScript/TypeScript

Currently delving into the world of JavaScript, I come from a background of working with statically typed languages. Naturally, I opted to dive into TypeScript instead of starting directly with JS. While TypeScript is great and addresses many issues presen ...

What is the best way to include multiple schema references in my mongoose schema?

I have a project in progress for a website that allows users to both take and upload tests. There are two types of users: Companies (who upload tests) and Candidates (who take tests). When I create a token, how can I reference both the schema of a Compan ...

Using jQuery to extract contact information from Google: A step-by-step guide

I'm currently using Google's API to access my contact list information and after logging the output in the console function fetch(token) { $.ajax({ url: "https://www.google.com/m8/feeds/contacts/default/full?access_token=" + token. ...

When using `element.addEventListener`, event.target will be the target

When working on a solution, I initially bound event listeners to multiple targets within the same container. I am curious to know if anyone has noticed considerable performance improvements by using just one event listener and leveraging the target of the ...

Using AngularJS to dynamically bind data based on certain conditions

I am managing an array of tasks that each have titles and labels. function Task(taskTitle, taskType) { this.title = taskTitle; this.type = taskType; } $scope.tasks = []; As I create different tasks with various types and add them to the array. In ...

Issue with Node Webpack identifying the "Import" statement

I'm diving into the world of Node and Webpack, but I'm struggling with getting my project to compile properly. Every time I try to load it in the browser, I encounter the error message: Uncaught SyntaxError: Unexpected token import. Let me share ...

Returning to the location in the file where the redirect function was invoked in the Express framework

In my current project, I am working on an Express app and facing a challenge. I need to redirect after collecting data in a function, complete the redirect, return the data, and then resume from where I left off. For instance: > res.redirect('my/ ...

Conceal Navigation with jQuery

Seeking assistance with jQuery for a new project. I'm trying to create a navigation menu that will automatically disappear after 3 seconds when a user enters the page. In its place, an arrow will be displayed instead of the original menu. Once the a ...

Unable to establish a connection with MongoDB Atlas utilizing Mongoose

I've recently delved into a MERN stack tutorial. The journey started with creating a react app, setting up a backend directory, installing essential dependencies like express, cors, and dotenv. Next came the server.js file where I added some code. How ...

Learn the steps to dynamically show a navbar component upon logging in without the need to refresh the page using Angular 12

After logging in successfully, I want to display a navbar on my landing page. Currently, the navbar only shows up if I reload the entire page after logging in. There must be a better way to achieve this without a full page reload. app.component.html <a ...

Determine if a field is empty using a Mongo and PHP query

Data: "field1" : { "sub_field" : [ ]} I am struggling to write a query that checks if the 'sub_field' is empty or not. Here is my attempt: $cursor = $collection->find( array('field1.sub_field' => array('$ne' => n ...

What is the best way to eliminate all records except for the most recent 10 in Mongodb or mongoose library

I've been trying to execute this query: db.date.remove({ _id:{ $not:{ $eq: ObjectId("570ba4f66931b8f21a8bf25f") }}, date:{ $lt: outdated } }) However, it's not functioning as expected. I want to exclude specifying ids. Is there a way t ...

Adding elements to an array using JavaScript

What is the correct way to add new values to an array like this? json = {"awesome":"45.22","supercool":"9876"} I attempted json.push("amazingness":"45.22");, but unfortunately it was not successful. ...

Issue with CSS transition not displaying ng-show elements properly

I'm currently working on incorporating a fade-in effect for text using the second solution from this source when using ng-show. Here is my HTML setup: <input ng-focus="hasFocus = true" ng-blur="hasFocus = false" type="text" placeholder="Cli ...

Instructions for displaying a React component in the <main> element when employing react-burger-menu

Check out my code here. Utilizing react-burger-menu has allowed me to successfully implement the sidebar feature. The sidebar functionality is working as expected. My current challenge involves figuring out how to open the content for Home or GG within ...