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

140
Vistas
How do I add values to an array in my mongo schema

My schema looks like this ...

  {
    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,
})

The userId is known. How do I add values to the user.answers array?

I've tried ...

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

as well as $push ... just I just on't know how to do this.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

First thing: You have to declare answerSchema before the main schema because it thrown the error:

ReferenceError: Cannot access 'answerSchema' before initialization

So your code has to be:

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

Then, into the query, if you use findByIdAndUpdate you can use the _id directly in the first parameter. Also you can use $push to add a new object, like this:

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

There is an example how $push works here

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