Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

222
Views
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 answers
Answer question

0

Try with $push operator:

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

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!