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

130
Visualizações
Push new Object inside a document array

I have this schema for my user

const userSchema = mongoose.Schema({
   
   firstName: {
        type: String,
      
    },

   notifications : [{
    description: String,
    status: {
        type: String,
        enum : ['read', 'unread'],
        default: 'unread'
    },
    dateAdded:{
        type: Date,
        default: Date.now
    }
    }],
})

supposedly I want to find the user _id first then insert a new object inside the new notification array. and it should look like this

{ 
  _id: ObjectId('123')
  firstName: 'John Doe'
  notifications:[
   {
     description: 'somedescription'
     status: 'unread'
 
   },
   {
     description: 'somedescription2'
     status: 'unread'
   }
   
  ]

}

How can I achieve this, assuming that the notification property is non existent in the user document first, i need to check if notification property is present else add the notification property and push the new object


  User.updateOne(
     { _id: userId },
     { $push: { notifications: {description: 'new notifications'}  } }
  )

this code is not working for me

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Use $addToSet operator to achieve that

  User.updateOne(
     { _id: userId },
     { $addToSet: { notifications: {description: 'new notifications'}  } }
  )

If that doesn't work try to add the default value too, and then that must work

  User.updateOne(
         { _id: userId },
         { $addToSet: { notifications: {description: 'new notifications',
  'status': 'unread'}  } }
 )
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