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;
2
Answers
To update the value of an object in a deeply nested array in Mongoose, you can use the positional $ operator combined with the dot notation. Here’s a basic example: