Sending data to mongodb using the fetch API and FormData method is a simple process that involves constructing

I have been trying to send data to mongoDB using the fetch API along with FormData, but encountering an error:

POST https://xxxxxxxxxxxxxxxxxxxxxxxx/upload 500 (Internal Server Error)

The form data in my EJS file appears as follows:

    <div id="image_data">        
        <form action="/upload" method="post">
            <p class="title_content">Enter data about your photo here:</p>
            <br>
            <input type="hidden" value=<%= username %> name="username" />
            <br>
            <input id="Base64IMG" type="hidden" value="" name="imgBase64" />
            <br>
            <label for="city">City: </label>
            <input id="city" placeholder="City" name="city" type="text" />
            <br />
            <label for="date">Captured on: </label>
            <input id="date" placeholder="Date" name="date" type="date" />
            <br />
            <textarea id="textarea" rows ="5" cols="40" placeholder="Describe your image briefly" name="description" ></textarea>
            <br>
            <input class="sub" type="submit" value="Upload"/>
        </form>
</div>

In my Javascript code where I use the fetch API:

function sendData(formData){
   fetch('/upload', {
      method: 'POST',
      body: formData
    })
      .then(function(response) {
        if (response.ok) {
          console.log('POST request sent successfully');
          console.log(response)
          alert("Success")
          // Additional processing steps after successful POST request
        } else {
          console.log('Error sending POST request');
        }
      })
      .catch(function(error) {
        console.log('Error sending POST request:', error.message);
      });
}

const form = document.querySelector('#image_data > form')

form.addEventListener('submit', function(event) {
   event.preventDefault()
   const formData = new FormData(form)
   
   if (navigator.onLine) {
      sendData(formData)
    } else {
.
.
.
}}

And this is my /upload route:

router.post("/upload", async (req,res) => {
  try {
    await img.create(req.body)
   if(true){
    res.status(200).json({message:true})
   }else{
    res.status(200).json({message:false})
   }
  } catch (error) {
      console.log(error.message);
      res.status(500).json({message: error.message})
  }
  console.log("Upload completed")
})

img has been imported from a mongoose schema like this:

const img = require("../database/picture");

If anyone can help me pinpoint what I might be doing wrong, it would be greatly appreciated :)

Update: In the server console, I see the following error message:

pictureData validation failed: description: Path `description` is required., date: Path `date` is required., city: Path `city` is required., imgBase64: Path `imgBase64` is required., username: Path `username` is required.

This is my Mongoose Schema:

const mongoose=require("mongoose")

const IMGSchema=new mongoose.Schema({
    username:{
        type:String,
        required:true
    },
    imgBase64:{
        type:String,
        required:true
    },
    city:{
        type:String,
        required:true
    },
    date:{
        type:String,
        type:Date,
        required:true
    },
    description:{
        type:String,
        required:true
    },
})

const img=new mongoose.model("pictureData", IMGSchema)

module.exports=img
´

Answer №1

Within your "pictureData" schema, the date field has been specified with a type declaration twice

date:{
    type:String,
    type:Date,
    required:true
}

This should be streamlined to only appear once, as follows:

date:{
    type:Date,
    required:true
}

Implementing this adjustment will ensure that validation functions correctly.

Answer №2

Implement a React.js form using the npm module, final-form

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 methods can I utilize to prevent pop-up errors from appearing in my javascript code?

Recently, I've been working on utilizing an innovative IBM tool called Presto that efficiently transforms traditional green screens into browser-based pages. While the process is effective, it involves some quirky behaviors. One particular challenge I ...

The writeToDB function is triggered only one time

I've encountered an issue with my node.js code where the writeToDB function is being called, but data is not inserted in the database after the first time. Can someone help me understand why? uploadInfoObject = { ProcessId: pid, Type: "type", ...

Identifying an Object by Clicking with the Mouse in three.js

After successfully loading 3 external models into my scene using the json loader, I am now trying to retrieve the name of the clicked model/object. Below is the code snippet that I used to load the models: var object_material = new THREE.MeshBasicMateria ...

How can I use appendChild to place two different elements into a single div?

While exploring similar questions on this topic, I have unfortunately not come across a solution that works for me. My challenge is trying to insert two a elements inside of a newly created div element using appendChild. However, I am unable to append them ...

Utilizing @casl/vue in conjunction with pinia: A guide to integrating these

I'm currently facing an issue with integrating @casl/ability and Vue 3 with Pinia. I'm unsure of how to make it work seamlessly. Here is a snippet from my app.js: import { createApp } from "vue" const app = createApp({}) // pinetree i ...

Attempting to send a request from the front-end to the back-end is resulting in a 404 endpoint error

I encountered an issue while sending a post request from the front end to the backend. The error message I received was: " Error: Request failed with status code 404 " " Had Issues POSTing to the backend, endpoint " My main concern is ...

The message vanishes upon refreshing the page

I've developed a socket.io web app. When I click on the button to send a message, the message appears briefly but disappears when the page refreshes unexpectedly. How can I prevent this random refreshing and ensure that socket.io saves my messages? B ...

The priority of custom attributes in HTML

There seems to be some ambiguity regarding whether data- attributes should be considered primary or secondary syntax. Is there a defined standard for this in major frameworks like Angular? For example, if an attribute is specified as both my-attr and dat ...

A Guide to Dynamically Updating Page Titles Using JavaScript in a Ruby on Rails Application

Every time I use Ajax to load a blog post on the webpage, I adjust the <title> to "My Blog - BLOGPOST_TITLE". It is worth mentioning that "My Blog - " also shows up in the application layout. My dilemma is, how do I inform my Javascript about the " ...

Display scroll bars over the position:absolute header

My container has content that exceeds its size in both directions. To see the issue, try scrolling horizontally and vertically on the table available here: The vertical scrollbar is visible as desired, except that it gets hidden behind the table header un ...

How can I enhance a JavaScript Calendar with more features?

I recently acquired a JavaScript and jQuery calendar from CodeCanyon, which can be found here. I am now faced with the task of integrating this calendar into my workplace website. The current calendar on our ASPX-based site is limited to read-only functio ...

Perform Action Only When Clicking "X" Button on JQuery Dialog

I have a dialog box with two buttons, "Yes" and "No", which trigger different functions when clicked. $('#divDialog').dialog({ modal:true, width:450, resizable: false, buttons: [{ text: 'Yes', ...

Creating balanced numerical values within the range of 0 to 1 using an array

Is there a way to create a set of numbers between 0 and 1 that is proportional to an array of sales with varying sizes? For instance, if the sales values are [1, 80, 2000], would it be possible to generate an array like [0.1, 0.4, 1]? ...

Creating a dynamic table in AngularJS with rotating values for rows and columns

I am seeking assistance in creating a table with a custom number of rows and columns. The table should have two input fields for specifying the number of rows and columns, and upon submission, the table should dynamically adjust to display the specified nu ...

The error encountered in the Node crud app states that the function console.log is not recognized as a

I am attempting to develop a CRUD application, however, I keep encountering an error message that states "TypeError: console.log is not a function" at Query. (C:\Users\Luis Hernandez\Desktop\gaming-crud\server\app.js:30:25) h ...

Click the button to instantly scroll to a particular word with highlighting, and with another click, jump to the next occurrence

In order to achieve the objective, simply click on a button that will search for and scroll to a specific word while highlighting it. The same button can be clicked again to find the next occurrence, and so on. If you need an example of how this works, ch ...

Encountering ENOENT error when accessing view file in NodeJS and Express

I've encountered a strange issue with my nodeJS application after refactoring it. The app launches without any problems, the API responds correctly. However, when I attempt to access "/", I receive the following error: Error: ENOENT, stat '/view ...

The angular datepicker functionality seems to be malfunctioning

unique-example encountering this error message: error TS2307: Cannot find module 'mydatepicker' also encountering a compile time error at this line: import { MyDatePickerModule } from 'mydatepicker'; report.module.ts : import ...

React and Material UI: Ensuring Proper Whitespace Handling in Strings

Exploring the use of Typography component from Material UI (https://material-ui.com/api/typography/) The main objective is to maintain the new lines and spaces in a saved string. For instance, if the string contains leading spaces and new lines, it shoul ...

Tips for simulating next/router in vitest for unit testing?

Struggling with creating basic tests for our Next.js application that utilizes the useRouter() hook, encountering errors when using vitest. In search of solutions to mock next/router for unit testing in conjunction with vitest. ...