Home > Software engineering >  I can't add elements in my schema ($addToSet)
I can't add elements in my schema ($addToSet)

Time:12-11

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.

CodePudding user response:

Try with $push operator:

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

  • Related