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

224
Visualizações
How can I Push only unique values into a array in mongoDB

I have a like table. and in that like table I have a array called videoLikes. I need to store the userData who had liked the video. so when I am trying to push an object with userId field into that array I got duplicate datas. my userId is unique on model so I need to push only a user once in that array. I have tried $addToSet operation but it's not working properly.

My usecase is when a user tried to like the video second time it won't push to that array.

{
  "videoId": 275,
  "likesCount": 4,
  "videoLikes": [
    {
      "userId": 149,
      "uid": "5B8slS9AqpeNMJWK5CgbwzdXhQ82",
      "_id": {
        "$oid": "625569ecd56d19a1954f5cc2"
      }
    },
    {
      "userId": 149,
      "uid": "5B8slS9AqpeNMJWK5CgbwzdXhQ82",
      "_id": {
        "$oid": "625569ecd56d19a1954f5cc4"
      }
    },
    {
      "userId": 149,
      "uid": "5B8slS9AqpeNMJWK5CgbwzdXhQ82",
      "_id": {
        "$oid": "625569ecd56d19a1954f5cc0"
      }
    },
    {
      "userId": 149,
      "uid": "5B8slS9AqpeNMJWK5CgbwzdXhQ82",
      "_id": {
        "$oid": "625569ecd56d19a1954f5cbe"
      }
    }
  ]
}
about 4 years ago · Santiago Gelvez
1 Respostas
Responde à pergunta

0

  • you should normalize the schema as when you know userId you know uid, this way you only have to store userId in array which is a integer and can be easily handled to make it unique.
  • you probably wanna learn about pre and post in mongoose and triggers in mongoDB.

using triggers you'll get time to check whether the user liking is previously done or not and perform action on its behalf. for checking whether a userId liked or not you can use Object instead of array example:

let schema=mongoose.Schema{
   videoId:Number,
   likesCount:Number,
   videoLikes={{uid:Number}}
}
about 4 years ago · Santiago Gelvez 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