0

I am creating a Form in React, using MUI and react-hooks-form and I cannot seem to make a successful POST request to my endpoint because something between what I am sending through my form and what Mongoose Schema should receive is not working. When I log the data, my checkbox values are log as an array and I have that checkbox group as an array of strings. Always Bad Requests. Hope someone can help me out.

User Schema

import mongoose from "mongoose";

const UserSchema = new mongoose.Schema({
  name: {
    type: String,
    required: [true, "Por favor escribe tu nombre"],
    maxLength: [60, "El nombre no puede tener mas de 50 caracteres"],
  },
  age: {
    type: Number,
    required: false,
  },
  email: {
    type: String,
    required: [true, "Por favor indicanos tu email"],
  },
  form: {
    type: String,
    enum: ["form1", "form2", "form3"],
  },
  pattern: {
    type: String,
    enum: ["pattern1", "pattern2", "pattern3"],
  },
  gadgets: [String],
});

export default mongoose.models.User || mongoose.model("User", UserSchema);

React Form (Not Refactored yet)

import React, { FC, ReactElement } from "react";
import { useForm } from "react-hook-form";
import axios from "axios";
import Box from "@mui/material/Box";
import Typography from "@mui/material/Typography";
import Button from "@mui/material/Button";
import TextField from "@mui/material/TextField";
import Radio from "@mui/material/Radio";
import RadioGroup from "@mui/material/RadioGroup";
import FormControlLabel from "@mui/material/FormControlLabel";
import FormControl from "@mui/material/FormControl";
import FormLabel from "@mui/material/FormLabel";
import FormGroup from "@mui/material/FormGroup";
import Checkbox from "@mui/material/Checkbox";

const Form: FC = (): ReactElement => {
  const {
    register,
    formState: { errors },
    handleSubmit,
    setValue,
  } = useForm();
  const onSubmit = async (data: any) => {
    console.log(data);
    axios
      .post("http://localhost:3000/api/users", {
        name: data.name,
        email: data.email,
        age: data.age,
        form: data.form,
        pattern: data.pattern,
        gadgets: data.gadgets,
      })
      .then(function (response) {
        console.log(response);
        if (response.status === 201 || 200) {
          setValue("name", "");
          setValue("email", "");
          setValue("age", "");
        }
      })
      .catch(function (error) {
        console.log(error);
      });
  };
  return (
    <Box
      component="form"
      onSubmit={handleSubmit(onSubmit)}
      sx={{}}
      noValidate
      autoComplete="on"
    >
      <Box component="div" sx={{ margin: "30px 0 30px 10px" }}>
        <Typography variant="body1">Datos Personales</Typography>
      </Box>
      <Box
        component="div"
        sx={{ m: 3, display: "flex", justifyContent: "space-around" }}
      >
        <TextField
          {...register("name", { required: true })}
          aria-invalid={errors.name ? "true" : "false"}
          size="small"
          id="name"
          label="Nombre Completo"
          variant="outlined"
          name="name"
          type="string"
          sx={{ width: "40ch" }}
        />
        {errors.name?.type === "required" && (
          <p role="alert">Name is required</p>
        )}
        <TextField
          {...register("email", { required: true })}
          aria-invalid={errors.email ? "true" : "false"}
          size="small"
          id="email"
          label="Email"
          variant="outlined"
          name="email"
          type="email"
          sx={{ width: "40ch" }}
        />
        {errors.email?.type === "required" && (
          <p role="alert">Email is required</p>
        )}
        <TextField
          {...register("age", { required: true })}
          aria-invalid={errors.age ? "true" : "false"}
          size="small"
          id="age"
          label="Edad"
          variant="outlined"
          name="age"
          type="number"
          sx={{ width: "10ch" }}
        />
        {errors.age?.type === "required" && <p role="alert">Age is required</p>}
      </Box>
      <Box
        component="div"
        sx={{
          m: 10,
          display: "flex",
          flexDirection: "column",
          justifyContent: "center",
        }}
      >
        <FormControl>
          <FormLabel id="demo-form-control-label-placement" sx={{ mb: 3 }}>
            Por favor Elija la Forma
          </FormLabel>
          <RadioGroup
            row
            aria-labelledby="demo-form-control-label-placement"
            name="form"
            defaultValue="top"
            sx={{
              display: "flex",
              flexDirection: "row",
              justifyContent: "space-around",
            }}
          >
            <FormControlLabel
              {...register("form")}
              value="form1"
              control={<Radio />}
              label="Forma 1"
              labelPlacement="top"
            />
            <FormControlLabel
              {...register("form")}
              value="form2"
              control={<Radio />}
              label="Forma 2"
              labelPlacement="top"
            />
            <FormControlLabel
              {...register("form")}
              value="form3"
              control={<Radio />}
              label="Forma 3"
              labelPlacement="top"
            />
          </RadioGroup>
        </FormControl>
        <FormControl>
          <FormLabel
            id="demo-form-control-label-placement"
            sx={{ mb: 3, mt: 3 }}
          >
            Por favor Elija la Tela
          </FormLabel>
          <RadioGroup
            row
            aria-labelledby="demo-form-control-label-placement"
            name="pattern"
            defaultValue="top"
            sx={{
              display: "flex",
              flexDirection: "row",
              justifyContent: "space-around",
            }}
          >
            <FormControlLabel
              {...register("pattern")}
              value="pattern1"
              control={<Radio />}
              label="Tela 1"
              labelPlacement="top"
            />
            <FormControlLabel
              {...register("pattern")}
              value="pattern2"
              control={<Radio />}
              label="Tela 2"
              labelPlacement="top"
            />
            <FormControlLabel
              {...register("pattern")}
              value="pattern3"
              control={<Radio />}
              label="Tela 3"
              labelPlacement="top"
            />
          </RadioGroup>
        </FormControl>
        {/* <FormControl>
          <FormLabel
            id="demo-form-control-label-placement"
            sx={{ mb: 3, mt: 3 }}
          >
            Por favor Elija los Accesorios
          </FormLabel>
          <RadioGroup
            row
            aria-labelledby="demo-form-control-label-placement"
            name="gadgets"
            defaultValue="top"
            sx={{
              display: "flex",
              flexDirection: "row",
              justifyContent: "space-around",
            }}
          >
            <FormControlLabel
              {...register("gadgets")}
              value="gadget1"
              control={<Radio />}
              label="Accesorio 1"
              labelPlacement="top"
            />
            <FormControlLabel
              {...register("gadgets")}
              value="gadget2"
              control={<Radio />}
              label="Accesorio 2"
              labelPlacement="top"
            />
            <FormControlLabel
              {...register("gadgets")}
              value="gadget3"
              control={<Radio />}
              label="Accesorio 3"
              labelPlacement="top"
            />
          </RadioGroup>
        </FormControl> */}
        <FormLabel id="demo-form-control-label-placement" sx={{ mb: 3, mt: 3 }}>
          Por favor Elija los Accesorios
        </FormLabel>
        <FormGroup
          sx={{
            display: "flex",
            flexDirection: "row",
            justifyContent: "space-around",
          }}
        >
          <FormControlLabel
            {...register("gadgets")}
            control={<Checkbox />}
            label="Accesorio 1"
            sx={{ mb: 3 }}
            name="gadgets"
            value="gadget1"
          />
          <FormControlLabel
            {...register("gadgets")}
            control={<Checkbox />}
            label="Accesorio 2"
            sx={{ mb: 3 }}
            name="gadgets"
            value="gadget2"
          />
          <FormControlLabel
            {...register("gadgets")}
            control={<Checkbox />}
            label="Accesorio 3"
            sx={{ mb: 3 }}
            name="gadgets"
            value="gadget3"
          />
        </FormGroup>
      </Box>
      <Box
        component="div"
        sx={{ m: 10, display: "flex", justifyContent: "center" }}
      >
        <Button variant="contained" type="submit">
          Enviar
        </Button>
      </Box>
    </Box>
  );
};

export default Form;

API Handler

import dbConnect from "../../../utils/dbConnect";
import User from "../../../models/User";

export default async function handler(req, res) {
  const { method } = req;

  await dbConnect();

  switch (method) {
    case "GET":
      try {
        const users = await User.find(
          {}
        ); /* find all the data in our database */
        res.status(200).json({ success: true, data: users });
      } catch (error) {
        res.status(400).json({ success: false });
      }
      break;
    case "POST":
      try {
        const user = await User.create(
          req.body
        ); /* create a new model in the database */
        res.status(201).json({ success: true, data: user });
      } catch (error) {
        res.status(400).json({ success: false });
      }
      break;
    default:
      res.status(400).json({ success: false });
      break;
  }
}

LOGGED DATA LoggedData Fronm Submit

AXIOS ERROR Axios Error

I tried reading Mongoose Docs, searching for videos on youtube. Several posts here in Stack Overflow and I cannot seem to get it.

2
  • are you receiving some data in your console.log(data)? and what is the error message you receive in the API call . and also can you add your code of your (post route for User model) Commented Nov 17, 2022 at 2:14
  • Hi @MelCarloIguis! Thanks for answering. I just updated the post with your requests. Commented Nov 17, 2022 at 10:54

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.