Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

159
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!