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

149
Views
¿Cómo agrego valores a una matriz en mi esquema mongo?

Mi esquema se ve así...

 { name: String, email: { type: String, required: true, index: true, }, age: { type: Number, default: 18, required: false, minlength: [2, 'Too short'], maxlength: [2, 'Too long'], }, role: { type: String, default: 'client', }, address: String, answers: [answerSchema], } const answerSchema = new Schema({ position: Number, slider: Number, scale: Number, })

El ID de usuario es conocido. ¿Cómo agrego valores a la matriz user.answers?

He intentado ...

 const updated = await User.findByIdAndUpdate( { _id: req.params.id }, { $set: {answers}}, { new: true } )

así como $push ... simplemente no sé cómo hacer esto.

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

0

Lo primero: debe declarar answerSchema antes del esquema principal porque arrojó el error:

 ReferenceError: Cannot access 'answerSchema' before initialization

Así que tu código tiene que ser:

 const answerSchema = new Schema({ ... }) // First const mainSchema = new Schema({ ... }) // Second

Luego, en la consulta, si usa findByIdAndUpdate , puede usar el _id directamente en el primer parámetro. También puede usar $push para agregar un nuevo objeto, como este:

 const updated = await User.findByIdAndUpdate( req.params.id, { $push: { answers:{ /* your object to insert here*/ } }}, { new: true } )

Hay un ejemplo de cómo funciona $push aquí

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!