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

139
Views
How do I add values to an array in my mongo schema

My schema looks like this ...

  {
    name: String,
    email: {
      type: String,
      required: true,
      index: true,
    },
    age: {
      type: Number,
      default: 18,
      required: false,
      minlength: [2, 'Too short'],
      maxlength: [2, 'Too long'],
    },
    role: {
      type: String,
      default: 'client',
    },
    address: String,
    answers: [answerSchema],
  }

const answerSchema = new Schema({
  position: Number,
  slider: Number,
  scale: Number,
})

The userId is known. How do I add values to the user.answers array?

I've tried ...

const updated = await User.findByIdAndUpdate(
    { _id: req.params.id },
    { $set: {answers}},
    { new: true }
  )

as well as $push ... just I just on't know how to do this.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

First thing: You have to declare answerSchema before the main schema because it thrown the error:

ReferenceError: Cannot access 'answerSchema' before initialization

So your code has to be:

const answerSchema = new Schema({ ... }) // First
const mainSchema = new Schema({ ... })  // Second

Then, into the query, if you use findByIdAndUpdate you can use the _id directly in the first parameter. Also you can use $push to add a new object, like this:

const updated = await User.findByIdAndUpdate(
    req.params.id,
    { $push: {
        answers:{ 
            /* your object to insert here*/
        }
    }},
    { new: true }
  )

There is an example how $push works here

about 4 years ago · Juan Pablo Isaza 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!