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

292
Vistas
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
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