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

291
Views
Insert to array if value is not present in more arrays

I am building a forum web app where user can like/dislike post of other users.

I have the following model, representing a Post:

[
  {
    _id:"0002253,
    title:"My first post",
    likes:[],
    dislikes:[]
  },
  {
    _id:"0002254,
    title:"My second post",
    likes:[],
    dislikes:[]
  },
   {
    _id:"0002255,
    title:"My third post",
    likes:[],
    dislikes:[]
  },
]

When a user sends a like or dislike, the latter's ID will be inserted into the corresponding array (like or dislike).

Each user can, for each post, insert only a like or a dislike (not both).

The query I used for the insert is the following:

 let vote_result = await Poll.updateOne(
        {
          _id: poll_id,
          $and: [
            { "likes": { $nin: [MY_ID] } },
            { "dislikes": { $nin: [MY_ID] }},
          ],
        },
        {
          $addToSet: {
            "likes": MY_ID,
          },
        },
      

So, theoretically, query should insert MY_ID in likes or dislikes array if and only if MY_ID is not present in either array.

The problem is that query still writes MY_ID in likes array (even if MY_ID is present in dislikes) and vice versa.

Let's suppose now I want to leave a 'Like' to a post:

Phase 1:

likes:[]    
dislikes:[] 

(I am able to like or dislike, it works.)

Phase 2:

likes: [MY_ID]
dislikes:[]

(I am not able send like again, it works, but I am still able to dislike - it should not allow me to vote again.)

about 4 years ago · Juan Pablo Isaza
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!