Search code examples
javascriptnode.jsmongodbmongoosemongoose-schema

How do I update an object in a deeply nested array of objects with mongoose?


I am trying to update the value of an object in a deeply nested array in mongoose, but havn't been able to come up with the correct syntax.

I have tried both atomic updates and the conventional way of updating items in mongodb still with no luck.

I want to update 'history[index].rideConfirmations[index].rideComplete.driverConfirmed

//driverHistorySchema.js
const mongoose = require("mongoose");

const DriversRideHistorySchema = new mongoose.Schema(
  {
    driverId: mongoose.Schema.ObjectId,
    driverName: String,
    history: [
      {
        date: String,
        rideConfirmations: [
          {
            riderConfirmationTime: String,
            driverConfirmationTime: String,
            riderName: String,
            riderId: mongoose.Schema.ObjectId,
            rideComplete: {
              riderConfirmed: Boolean,
              driverConfirmed: Boolean,
            },
          },
        ],
      },
    ],
  },
  { timestamps: true, collection: "driversRideHistory" }
);

module.exports = mongoose.model("DriversRideHistory", DriversRideHistorySchema);


I want to update 'history[index].rideConfirmations[index].rideComplete.driverConfirmed

router.put("/rideHistory/completeRide", async (req, res) => {
  try {
    const { driverId, dateIndex, riderIndex } = req.body;

    await DriversHistoryModel.findOneAndUpdate(
      {
        driverId: driverId,
      },
      {
        $set: {
          "history.$[dateIndex].rideConfirmations.$[riderIndex].rideComplete.driverConfirmed": true,
        },
      },
      { arrayFilters: [{ dateIndex: dateIndex }, { riderIndex: riderIndex }] }
    );

    return res.status(200).send("Ride Completed Successfully");
  } catch (err) {
    console.log(err);
    return res
      .status(404)
      .send("An error occured while processing this request");
  }
});

module.exports = router;

Solution

  • router.put("/rideHistory/completeRide", async (req, res) => {
      console.log(req.body);
      try {
        const { driverId, dateIndex, riderIndex } = req.body;
        //Update history on driver's profile first
        const driver = await DriversHistoryModel.findOne({
          driverId,
        });
    
        const dateToUpdate =
          driver.history[dateIndex].rideConfirmations[riderIndex];
    
        dateToUpdate.rideComplete.driverConfirmed = true;
    
        await driver.save();
    
        return res.status(200).send(dateToUpdate);
    
    
        return res.status(200).send("Ride Completed Successfully");
      } catch (err) {
        console.log(err);
        return res
          .status(404)
          .send("An error occured while processing this request");
      }
    });