Home > Blockchain >  How can i take date inputs from user and save it to mongoDB?
How can i take date inputs from user and save it to mongoDB?

Time:08-07

I have successfully taken date from user but after "POST" the database saves null. I've been stuck here for so long. I really need help here!! Since the date parts never got store, I didn't validate them.

This is what Database Saves

  {
    _id: new ObjectId("62ee76b6504db006f1bbb3d2"),
    taskName: 'hello',
    assignTo: 'world',
    startedOn: null,
    dueDate: null,
    taskDescription: 'asd',
    requiredFiles: 'asd',
    __v: 0
  }
]

This is my Form where User picks the date

function Popup(props) {
  const history = useNavigate();
  const { openPopup, setOpenPopup } = props;
  const [startDate, setStartDate] = useState(new Date());
  const [endDate, setDueDate] = useState(new Date());
  const [employeeName, setEmployeeName] = useState({
    taskName: "",
    assignTo: "",
    startedOn: "",
    dueDate: "",
    taskDescription: "",
    requiredFiles: "",
  });

  const clgdata = (e) => {
    console.log(e.target.value);
    const { name, value } = e.target;
    setEmployeeName((newData) => {
      return { ...newData, [name]: value };
    });
  };

  const changeStartDate = (newValue) =>{
    setStartDate((prev)=>{
      return{...prev, startDate : newValue}
    })
  }

  const changeDueDate = (newValue) =>{
    setDueDate((prev)=>{
      return{...prev, endDate : newValue}
    })
  }

  const createTask = async (e) => {
    e.preventDefault();
    const {
      taskName,
      assignTo,
      startedOn,
      dueDate,
      taskDescription,
      requiredFiles,
    } = employeeName;

    const res = await fetch("http://localhost:3001/createtask", {
      method: "POST",
      headers: {
        "content-type": "application/json",
      },
      body: JSON.stringify({
        taskName,
        assignTo,
        startedOn,
        dueDate,
        taskDescription,
        requiredFiles,
      }),
    });
    const data = await res.json();
    console.log(data);
    if (res.status === 404 || !data) {
      alert("Please Complete the Empty Fields");
    } else {
      alert(`Task has been assigned to the employee`);
      setOpenPopup(false);
      history("/task");
    }
  };

  return (
    <>
      <Dialog open={openPopup}>
        <DialogTitle>
          <div className="title">
            <ArrowBackIcon
              className="leftArrow"
              onClick={() => setOpenPopup(false)}
            >
              close
            </ArrowBackIcon>

            <h3>Create a task</h3>
          </div>
        </DialogTitle>
        <DialogContent>
          <div className="form">
            <TextField
              className="form-btn"
              name="taskName"
              type="text"
              id="outlined-basic"
              label="Task Title"
              variant="outlined"
              onChange={clgdata}
              value={employeeName.taskName}
            />
            <TextField
              name="assignTo"
              type="text"
              onChange={clgdata}
              value={employeeName.assignTo}
              className="form-btn"
              id="outlined-basic"
              label="Select an Employee"
            ></TextField>
            <div className="Time">
              <LocalizationProvider dateAdapter={AdapterDateFns}>
                <DatePicker
                  name="startedOn"
                  className="form-btn startedOn"
                  label="Started On"
                  type="date"
                  value={startDate.startDate}
                  onChange={changeStartDate}
                  renderInput={(params) => <TextField {...params} />}
                />
              </LocalizationProvider>
              <LocalizationProvider dateAdapter={AdapterDateFns}>
                <DatePicker
                  className="form-btn startedOn"
                  name="dueDate"
                  label="Due Date"
                  value={endDate.endDate}
                  onChange={changeDueDate}
                  renderInput={(params) => <TextField {...params} />}
                />
              </LocalizationProvider>
            </div>
 </div>
            <TextField
              className="form-btn"
              id="outlined-basic"
              label="Task Description"
              variant="outlined"
              name="taskDescription"
              type="text"
              onChange={clgdata}
              value={employeeName.taskDescription}
            />
            <TextField
              className="form-btn"
              id="outlined-basic"
              label="Required Files"
              variant="outlined"
              name="requiredFiles"
              type="text"
              onChange={clgdata}
              value={employeeName.requiredFiles}
            />
          </div>
        </DialogContent>
        <DialogActions>
          <Button onClick={createTask}>Submit</Button>
        </DialogActions>
      </Dialog>
    </>
  );
}

export default Popup;

This is my userSchema of MongoDB

const mongoose = require("mongoose");

const userSchema = mongoose.Schema({
  taskName: {
    type: String,
    required: true,
  },
  assignTo: {
    type: String,
    required: true,
    unique: true,

  },
  startedOn: {
    type: Date,
    // required: true,
  },
  dueDate: {
    type: Date,
    // required: true,
  },
  taskDescription:{
      type: String,
      required: true,
  },
  requiredFiles:{
      type: String,
      required: true,
  }
});

const createTask = mongoose.model("createTask", userSchema);

module.exports = createTask;

This is my router.JS

router.post("/createtask", async (req, res) => {
 const {
    taskName,
    assignTo,
    startedOn,
    dueDate,
    taskDescription,
    requiredFiles,
  } = req.body;

  if (!taskName || !assignTo || !taskDescription || !requiredFiles) {
    res.status(404).json("Please Complete the Empty Fields");
  } else {
    const newTask = new createTask({
      taskName,
      assignTo,
      startedOn,
      dueDate,
      taskDescription,
      requiredFiles,
    });

    await newTask.save();
    res.status(201).json(newTask);
    console.log(newTask);
  }
});

CodePudding user response:

There are several inconsistencies in your code.

Remove these two lines:

const [startDate, setStartDate] = useState(new Date());
const [endDate, setDueDate] = useState(new Date());

Update the initialization:

const [employeeName, setEmployeeName] = useState({
  taskName: "",
  assignTo: "",
  startedOn: new Date(),
  dueDate: new Date(),
  taskDescription: "",
  requiredFiles: "",
});

Update the handlers:

const changeStartDate = (newValue) => {
  setEmployeeName((prev) => {
    return { ...prev, startedOn: newValue };
  });
};

const changeDueDate = (newValue) => {
  setEmployeeName((prev) => {
    return { ...prev, dueDate: newValue };
  });
};

Update the DatePickers:

<LocalizationProvider dateAdapter={AdapterDateFns}>
    <DatePicker
        name="startedOn"
        className="form-btn startedOn"
        label="Started On"
        type="date"
        value={employeeName.startedOn}
        onChange={changeStartDate}
        renderInput={(params) => <TextField {...params} />}
    />
    </LocalizationProvider>
    <LocalizationProvider dateAdapter={AdapterDateFns}>
    <DatePicker
        className="form-btn startedOn"
        name="dueDate"
        label="Due Date"
        value={employeeName.dueDate}
        onChange={changeDueDate}
        renderInput={(params) => <TextField {...params} />}
    />
</LocalizationProvider>

Now createTask sends startedOn and dueDate to the server.

  • Related