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

214
Vistas
I can't add elements in my schema ($addToSet)

I have such a scheme. When using the command, I want new items to be added there

const userSchema = new mongoose.Schema({
    _id: {                      //user id
        type: String,
        required: true,
    },
    books: [{                  //book that user uses    
            _id: {               //book id
                type: Number,
                required: true,
            },
            lessons: [{          //lessons of the book with progress
                type: String,
                required: true,
            }],
    }],
})

I am trying to add them this way.

await userSchema.findByIdAndUpdate(author.id, { $addToSet: { books: {_id: bookid, lessons: progress} } })

bookid - is int value incremented by one. progress - array of strings

But only an array of lessons is written to the base, without id. When I add only the id, then not the id is added, but an array of lessons. I've spent several hours already and I can't figure out why it doesn't want to add everything to the array. Please help.

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

Try with $push operator:

await userSchema.findByIdAndUpdate(author.id, {
  $push: { 
    books: {
      _id: bookid,
      lessons: progress
    }
  } 
})

over 4 years ago · Santiago Trujillo 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