1

I am trying to figure out how to update a nested array that is within an array with Mongoose. In my User collection, I have a customer array that contains customer info, along with a nested fleet array that holds the customer's fleet equipment. I am trying to update the fleet array via a PUT request, but am having difficulties.

I partially think it is not possible to update a nested array within an array like this, and maybe I should create a separate Schema for the customer and fleet. Anyways, here is what my User Schema looks like currently:

{
    "username": "xps_maint",
    "password": "0000",
    "registerDate": "2018-10-24T13:37:12.093Z",
    "_id": "5bd07612d63de74932734d92",
    "customer": [
        {
            "name": "Freight  Service ",
            "email": "info@fsllc.com",
            "dotInterval": "90 days",
            "fleet": [
                {
                    "unitType": "Box Truck",
                    "unitNumber": "BT-61318",
                    "vinNumber": "1XXXYYYUUUZZ3222",
                    "_id": "5bd0aef1e2abd64b12e0ab42"
                },
                {
                    "unitType": "Cargo Van",
                    "unitNumber": CV-78453",
                    "vinNumber": "4ZZYYYTTUZZ3JK2",
                    "_id": "5bd0aef1e2arg64b15e0ab43"
                }
            ],
            "_id": "5bd0821f79f9454b06b2c2bf"
        }
    ],
    "__v": 0
}

Here is my PUT route to update the fleet array:

router.put('/customers/fleet/:equipmentid', customer_controller.customer_update_fleet);

And finally here is the what the fleet update controller looks like:

exports.customer_update_fleet = (req, res) => {
    const { body, params } = req;
    const { unitType, unitNumber, vinNumber } = body;
    const { equipmentid } = params;

    const updatedEquipment = 
    {
        unitType: unitType,
        unitNumber: unitNumber,
        vinNumber: vinNumber,
    }

    User.updateOne({ 'customer.$.fleet': { _id: equipmentid }}, { $set: { 'customer.$.fleet': { updatedEquipment} } }, (err) => {
        if (err)
            throw err;
        else 
            res.send('Success!!');
    });
}

I thought this might of worked, because I have a similar PUT route that updates just the customer array in the User Schema via Model.updateOne(). However this does not seem to work the same way when trying to go deeper into the nested fleet array within each customer.

I may be approaching this all wrong, so I am all ears on a better way to model the User Schema. I do partially think that it is not too good to have arrays nested deep in Schemas like this, they seem like a pain to update. Thanks in advance for reading!

maison.m
  • 813
  • 2
  • 19
  • 34

0 Answers0