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

132
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
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