skip to Main Content

I want to mark a as turf booked or not using put request. I am unable to update the data. I am using .save() method to update the data.

app.put("/turf/:turfId/day/:dayIndex/time-slot/:timeSlotId", async (req, res) => {
  const tid = parseInt(req.params.turfId);
  const dayIndex = parseInt(req.params.dayIndex);
  const timeSlotId = parseInt(req.params.timeSlotId);
  const booked = req.body.booked;

  const turf = await turfData.findOne({ turfId: tid });
  if (!turf) {
    res.status(404).send("Turf not found");
    return;
  }
  const day = turf.days[dayIndex];
  if (!day) {
    res.status(404).send("Day not found");
    return;
  }
  const timeSlot = day.timeSlots.find((t) => t.id === timeSlotId);
  if (!timeSlot) {
    res.status(404).send("Time slot not found");
    return;
  }
  timeSlot.booked = booked; 
  
  await turf.save();
  res.send(turf);
});

enter image description here

I am getting response 200 OK on thunder client but I dont know why it is not getting updated in monogoDB.

enter image description here

Someone who might have gone through similar issue.

2

Answers


  1. I can see that you are saving the turf but to save it in the DB, you have to create it too.

    const createTurf = new turfData({
        // data to be saved
    })
    await createTurf.save()
    

    You can try this.

    Login or Signup to reply.
  2. Try to reference the element to update directly like so:

    app.put(
      '/turf/:turfId/day/:dayIndex/time-slot/:timeSlotId',
      async (req, res) => {
        const tid = parseInt(req.params.turfId);
        const dayIndex = parseInt(req.params.dayIndex);
        const timeSlotId = parseInt(req.params.timeSlotId);
        const booked = req.body.booked;
    
        const turf = await turfData.findOne({ turfId: tid });
        if (!turf) {
          res.status(404).send('Turf not found');
          return;
        }
        if (dayIndex >= turf.days.length || !turf.days[dayIndex]) {
          res.status(404).send('Day not found');
          return;
        }
        const day = turf.days[dayIndex];
        const timeSlot = day.timeSlots.find((t) => t.id === timeSlotId);
        if (!timeSlot) {
          res.status(404).send('Time slot not found');
          return;
        }
        turf.days[dayIndex].find((t) => t.id === timeSlotId).booked = booked;
    
        await turf.save();
        res.send(turf);
      }
    );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search