Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

163
Vistas
How to update an array field on mongodb by pushing it if the element is not present and if it is present update it?

I am working on a IT ticketing system where every time a new comment or a note has been added to a ticket a notification needs to be send to the user who is following the ticket. Below code only inserts new ticket in list of tickets followed by the user if it is not already present, however if it is present it ignores it. What I need to do is if the ticket that has just been updated is already present, change clicked field to false. In my application's frontend, when user clicks the notification icon it will change clicked to TRUE but when a new comment is added clicked needs to be changed to FALSE so that the user gets notification that comment has been added to the same ticket. How do I go about achieving it?

const ReqNotificationSchema = new Schema({
  user: { type: Schema.Types.ObjectId, ref: "User" },
  notifications: [
    {
      request: { type: Schema.Types.ObjectId, ref: "Request" },
      clicked: { type: Boolean, default: false },
    },
  ],
});


if(updated){

await ReqNotificationModel.findOneAndUpdate(
          {
            user: follower.user,
            "notifications.request": { $ne: updated._id },
          },
          {
            $push: { notifications: { request: updated._id, clicked: false } },
          },
          { new: true }
        );
}
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

I wasn't able to do it in one step , so I tried in a 2 step approach.

const notification = await ReqNotificationModel.findOne({
          user: follower.user,
        });
        let index = notification.notifications
          .map((obj) => obj.request.toString())
          .indexOf(updated._id.toString());

        notification.notifications[index].clicked = false;

        
        await notification.save();
 });
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda