• Empleos
  • Sobre nosotros
  • profesionales
    • Inicio
    • Empleos
    • Cursos y retos
  • empresas
    • Inicio
    • Publicar vacante
    • Nuestro proceso
    • Precios
    • Evaluaciones
    • Nómina
    • Blog
    • Comercial
    • Calculadora de salario

0

155
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.

about 3 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
    }
  } 
})

about 3 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 Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recomiéndame algunas ofertas
Necesito ayuda