Natan Salmon
Natan Salmon

Reputation: 1

Mongoose - findByIdAndUpdate not working as expected

I am encountering a weird issue, when I try to perform a findByIdAndUpdate query, the query does not perform the $set as expected.

(I am using NestJS and Mongoose)

  async joinManyToCrisis(crisisId: string, vols: Omit<JoinCrisisDTO, "crisisId">[]) {
    const volunteerObjects = vols.map((v) => ({
      _id: new mongoose.Types.ObjectId(v.volunteerId),
      SUV_vehicle: Boolean(v.joinWithSUV),
      time_of_arrival: new Date(), //when we will have a map we will change it so it will be based on arrival time calculation by location
      has_arrived: false,
      positions: [],
      quit: false,
    }));

    const volsObjIds = volunteerObjects.map((v) => v._id);

    console.log(volsObjIds); //prints the ids correctly
    console.log(volunteerObjects); //prints the objects correctly as the schema expects

    return await this.crisisModel.findByIdAndUpdate(
      crisisId,
      {
        $set: {
          volunteers: {
            $concatArrays: [
              volunteerObjects,
              {
                $filter: {
                  input: "$volunteers",
                  as: "vol",
                  cond: { $not: { $in: ["$$vol._id", volsObjIds] } },
                },
              },
            ],
          },
        },
      },
      { new: true }
    );
  }

this query above, returns the updated crisis as expected, however the volunteers array returns empty.

I am trying to replace the volunteer if the volunteer already exists in the volunteers array, if it does not exist I am trying to add it to the array. (Thats why I used the $filter)

Upvotes: 0

Views: 39

Answers (0)

Related Questions