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

Cannot find the appended element in an AJAX call using jQuery

Within the code snippet, .moneychoose is described as the div in moneychoose.jsp. Interestingly, $(".moneychoose") cannot be selected within the ajax call. $("input[name='money']").on("click", function() { if ($("#money").find(".moneychoose" ...

Developing an easily optimized library using rollup to remove unnecessary code branches

I'm currently in the process of developing a component library using rollup and Vue with the goal of making it tree shakable for others who import it. The configuration setup is outlined below: Here's a snippet from package.json { "name": "re ...

Setting the initial viewer position in Panolens: A step-by-step guide

I've been working on setting the initial viewer position for panolens.js for a while now. Here's how the set-up looks: const panoPhoto1 = 'https://conceptcityiasi.ro/assets/images/tours/tip1/apartamente-noi-de-vanzare-iasi-dacia-1_camera-ti ...

What is the best way to keep the heights of two divs in sync?

Is there a way to make two divs have the same height, even though their content determines their individual heights? I am looking for a solution that doesn't involve using a table or a parent div. I'm new to JavaScript, so I'm hoping there i ...

jqueryajax function returns a boolean value upon completion

Recently, I developed a container method to handle an ajax request: function postRating(formData) { $.ajax({ type: "POST", url: '/api/ratings', data: formData }) .done(function () { return true ...

Are there any user interface frameworks available that can replicate the aesthetic of a Mac application?

I've been searching high and low but I haven't come across any answers yet. It caught my attention that the wunderlist mac app was developed using HTML/CSS/JS, but I'm curious if they incorporated a pre-existing UI JavaScript framework into ...

Javascript Google Maps API is not working properly when trying to load the Gmap via a Json

Trying to display a map using Gmaps and Jquery Ajax through JSON, but encountering difficulty in getting the map to appear on the page. The correct coordinates are being retrieved as confirmed by testing in the console. Puzzled by why it's not showin ...

The route in my Node.js Express application appears to be malfunctioning

I am facing an issue with my app.js and route file configuration. Here is my app.js file: const express = require('express'); const app = express(); const port = process.env.PORT || 8080; const userRoute = require('./routes/user.route' ...

Positioning an HTML table with the use of a for loop in JavaScript

Detail of the project: -Utilizing a javascript for loop, my program extracts data from an external javascript array titled "arrays.js" and organizes it into an HTML table. The goal is to align the appropriate data under the "Date Name Address Amount" colum ...

The system encountered an error stating that the required component "Footer" in the main directory was not located in the specified node_modules

Issue I'm Facing: Error found in components/main/Footer within the file path: ./node_modules/babel-loader/lib!./node_modules/vue-loader/lib/selector.js?type=script&index=0!./src/App.vue Components Tree as shown in the screenshot below: Cod ...

What is the best way to manipulate and update individual counters in React components?

I developed a ticket ordering system for a project, but encountered an issue where increasing the quantity of one ticket also resulted in the incrementation of the other ticket's counter. I suspect this occurs because only one value is stored in the s ...

What is the best way to add query parameters to router.push without cluttering the URL?

In my current project, I am using NextJS 13 with TypeScript but not utilizing the app router. I am facing an issue while trying to pass data over router.push to a dynamically routed page in Next.js without compromising the clarity of the URL. router.push({ ...

Adjust the size of the font in your Bootstrap Table

I've been utilizing the Bootstrap table feature and it's been fantastic, but I've encountered an issue with changing the font size. I've referred to the example on , however no matter what adjustments I make to the size, it doesn' ...

navigate to the subsequent array element by clicking in JavaScript

My apologies if my explanation is unclear or if the code seems complicated, I'm still in the learning process. I am attempting to showcase data that is stored in an array. The objective is to have this data displayed upon clicking a button and then sh ...

iOS devices will not scroll horizontally if there is a div that scrolls vertically within a div that scrolls horizontally

Picture a div that scrolls horizontally, housing two vertical-scrolling divs. You'll need to scroll left and right to navigate, then up and down inside the inner divs to read the content. /* RESET TO MINIMUM */ body, html { height: 100%; mar ...

Issue: A problem has arisen with the element type, as it was supposed to be a string for built-in components but is currently undefined. This error is being encountered

Help needed: Error in my code! I am working with three files: HeaderOption.js, HeaderOptions.js, Search.js This is the content of HeaderOptions.js import HeaderOption from "./HeaderOption"; import DotsVerticalIcon from "@heroicons/react/o ...

The like button seems to be malfunctioning and I'm not sure what the issue is

I've added the ability for users to like my posts, but it's not working as intended. Here's the code snippet I used: models.py class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField(blank=Tru ...

Delaying consecutive calls to query on mouse enter event in React

Currently, I have a React component from antd that utilizes the onMouseEnter prop to make an API query. The issue arises when users hover over the component multiple times in quick succession, which floods the network with unnecessary API calls. To prevent ...

Vue.js and the hidden input value that remains unseen

I am currently developing a shopping list application using Vue.js and I was wondering if there is a conventional method to achieve my requirements. My app consists of a list of items with add and delete buttons: https://i.stack.imgur.com/yQfcz.png const ...

Modify the size value dialog during runtime

I am attempting to create a property or method that can change the size of my container dialog built using Vuetify. Initially, I need it to look like this: <v-flex xs12 md10> I believe that by creating a variable property, I can dynamically change ...