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

129
Views
Empuje el nuevo objeto dentro de una matriz de documentos

Tengo este esquema para mi usuario.

 const userSchema = mongoose.Schema({ firstName: { type: String, }, notifications : [{ description: String, status: { type: String, enum : ['read', 'unread'], default: 'unread' }, dateAdded:{ type: Date, default: Date.now } }], })

supuestamente quiero encontrar el _id del usuario primero y luego insertar un nuevo objeto dentro de la nueva matriz de notificaciones. y debería verse así

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

¿Cómo puedo lograr esto, suponiendo que la propiedad de notificación no existe en el documento de usuario primero, necesito verificar si la propiedad de notificación está presente; de lo contrario, agregue la propiedad de notificación y presione el nuevo objeto?

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

este codigo no me funciona

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Use el operador $addToSet para lograr eso

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

Si eso no funciona, intente agregar el valor predeterminado también, y luego eso debe funcionar

 User.updateOne( { _id: userId }, { $addToSet: { notifications: {description: 'new notifications', 'status': 'unread'} } } )
about 4 years ago · Juan Pablo Isaza Report
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!