'Mongoose update object in array by query

Want to update object in array if value Status:"online", is Status:"online" then do not want to update it. My API will find collection by name then will check element in array to check it status online or offline and will update accordingly I have the following mongoDB collection:

id
:6268f97cc8662d6024d03389
GPS_Tracker
:
Array

    0
    :
    Object
    1
    :
    Object
        endTime
        :" 3:17:01 am"
        startTime
        :" 3:17:01 am"
        startDate
        :"Apr 27th 22"
        StartedGPSCoords
        :
        Object
        StoppedGPSCoords
        :
        Object
        Status
        :"offline"
        statusCounter
        :1
        name
        :"Yana Aliyev"
    2
    :
    Object
        endTime
        :" 3:18:07 am"
        startTime
        :" 3:18:07 am"
        startDate
        :"Apr 27th 22"
        StartedGPSCoords
        :
        Object
        StoppedGPSCoords
        :
        Object
        Status
        :"online"
        statusCounter
        :1
        name
        :"Yana Aliyev"

name
:"Yana Aliyev"

I need to find and update only object in array where Status is online.

My API looks like the following:

route.post("/update-partner-gps", (req, res) => {
  partnerGPS_coords
    .find({ name: req.body.fullName })
    .select({ GPS_Tracker: { $elemMatch: { Status: "online" } } })
    .update({
      endTime: moment().format(" h:mm:ss a"),
      StoppedGPSCoords: {
        lat: "500",
        lng: "4005055",
      },
    })
    .then((response) => res.status(200).send({ response }))
    .catch((error) => res.status(500).send({ error }));
  // .select({
  //   GPS_Tracker: { $elemMatch: { Status: "online" } },
  // });
});

I tried almost everything, not sure if it is possible to update object in array conditionally



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source