Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

164
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda