Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Comercial
    • Calculadora

0

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

9 months ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

Try with $push operator:

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

9 months ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos