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

What is the process for generating a submatch for this specific expression?

Trying to extract account status information using a regular expression in the DOM. Here is the specific string from the page: <h3>Status</h3><p>Completed</p> Current regular expression being used: <h3>Status</h3>[&bs ...

Is your URL getting cut off in jQuery?

How can I properly display a URL in an HTML table without it getting truncated? I'm attempting to show it within a table using jQuery, but it seems to be cutting off the URL. Here's a snippet of my code. Any suggestions on how to fix this? <! ...

React slick does not display arrows when there are 4 or more photos

I am facing an issue where the next and previous arrows are not appearing when I have 4 or more photos on react-slick. However, they show up fine when there are 3 or fewer photos. You can view my code at this link: https://codesandbox.io/s/wyyrl6zz3l ...

Issue with Material UI select component not displaying the label text

I've been struggling with Material UI's "Select" for quite some time now - spent about 10 hours trying to make it work the way I want. Any help would be greatly appreciated. This question is connected to a previous one: Select MenuItem doesn' ...

Utilize data from two distinct JSON sources that are updated at varying intervals, and display the combined results in an ng-repeat

I am currently working on creating a status list that pulls data from two separate JSON sources. The main purpose of this list is to show general information from the first source, while also indicating a status color based on the number of people in the s ...

Instead of pushing multiple items, focus on pushing only one item at a time

I've encountered an issue while attempting to add a new item to my favlist. Using a for loop, I check if the item already exists in the favlist. However, instead of adding the new item only once, it ends up being added multiple times. What would be ...

React Timer App: The setInterval function is being reset after each render operation

I'm currently working on a straightforward timer application that will begin counting seconds when a button is clicked. To implement this, I am utilizing react hooks. import React, { useState } from 'react' function Timer() { const [sec ...

Display a preview image at the conclusion of a YouTube video

I am currently working on an iOS device and have a Youtube video thumbnail that, when clicked, disappears and the video automatically plays in fullscreen mode using an iframe. It's working perfectly. Now, I would like to know how I can make the thumb ...

My project in WebStorm encounters a setback due to the updated release of Typescript 5+

Recently, I had to upgrade my TypeScript version from 4.9.5 to 5.1.3 because one of the libraries I'm using made a fix that required a newer TypeScript version. After the update, TypeScript started throwing errors for console calls and React event di ...

The search box output will be the same as the JSON result

I have a server in Node.js that is able to read and process a JSON file containing various data, including unique user IDs. I have incorporated a search box into my HTML page, and I am seeking assistance with creating a jQuery method (which will require AJ ...

What could be causing the directive to not trigger the controller method of mine?

Having trouble with my directive not calling the controller method. Here's the code I'm using: Controller: exports.controller = ['$scope', function($scope) { $scope.addParamter = function () { console.log("here ...

Is it possible to consolidate React and React-DOM into a unified library instead of having them separate?

Is it possible to combine React.JS and React-DOM.JS into a single library? In all the web applications I've encountered, we always have to import both libraries separately. Have there been any cases where either of these libraries can be used on its ...

Has Chrome's console disappeared?

After reinstalling Chrome and opening the dev tools with F12, I encountered an error with the following code: console.debug('test'); The error message displayed was Uncaught ReferenceError: console is not defined(…) This issue persisted acro ...

Ways to terminate a running child process in npm

Within my package.json file, I have a debug script that launches a Node application. This entire NPM script is initiated by a test, and this test must terminate the debug script once it completes. When I use npm run debug and try to kill the process, the ...

Using ES6 without the need for jQuery, populate a select element with JSON data using Javascript

I have a json-formatted dataset that I want to incorporate into my select options. Here is the data: { "timezones": { "country": "Africa", "tz": "Africa/Abidjan" }, { "country": "America", "tz": "America/ ...

Can a universal Save File As button be created for all web browsers?

Currently, I am in the process of developing a music player on the client side and I am seeking a method to save playlists that include mp3 data. Concerns with localStorage The restriction of a 5mb limit for localStorage makes it impractical for my needs. ...

Guide to using get() and res.sendFile() function to redirect webpages

Why is the page not redirecting properly? In my index.html file, I have this script: $.get( "/loginPage", function( data ) {}); The purpose of this script is to check if a user is logged in. If they are, it should redirect them to the lobbyPage. This is ...

Adding options to a select element using JavaScript dynamically

Is there a way to create a dynamic select list for year values using JavaScript? <form action="something"> some other fields <select id="year"> </select> </form> ...

AngularJS Object Comparison: A Comprehensive Guide

My form initiates a GET request to the server upon loading, receiving data that is stored in 'master' and then copied to 'local' as shown below. $scope.dirty = false; init(data); function init(data) { $scope.master = angular.copy ...

When working with Angular 12, the target environment lacks support for dynamic import() syntax. Therefore, utilizing external type 'module' within a script is not feasible

My current issue involves using dynamic import code to bring in a js library during runtime: export class AuthService { constructor() { import('https://apis.google.com/js/platform.js').then(result => { console.log(resul ...