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

158
Views
UpdateOne MongoDB with push using value from another field

I'm trying to push an existing field of my document to my array. this is my schema :

var mySchema = new Schema({
    level: {
        type: Number,
        default: 1
    },
    mHierarchy: [
        {
            userId: {
                  type: mongoose.Types.ObjectId
            },
            index: {
                  type: Number
            }
         }
    ]
})

i'm trying to use UpdateOne and push to mHierarchy and set outer level to the index.

what I've tried so far:

MySchema.updateOne(
{'_id': mySchemaId},
$push: {
        referredHierarchy: {
                        userId: mongoose.Types.ObjectId(id),
                        index: '$$level'
                        }
        }
)}

I also tried this:

let setQuery= {}
setQuery['mHierarchy.' + level + '.userId']= mongoose.Types.ObjectId(userId)
setQuery['mHierarchy.' + level + '.index']= '$$temp'
MySchema.updateOne(
                    {'_id': mySchemaId},
                    {
                        $set: setQuery
                    },
                    {let: {temp: '$level'}}
                )

and none of the above works and I get this error :

"CastError: Cast to Number failed for value \"$$temp\" (type string) at path \"index\""

how can I achieve this using mongoose?

NOTE: I use MongoDB 5 and "mongoose": 6.0.8

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

0

You will need first to add this field to the pipeline with the $set operator. Try this one:

MySchema.updateOne({ _id: mySchemaId }, {
$set: {
  index: "$level",
}},{
$push: {
  referredHierarchy: {
    userId: mongoose.Types.ObjectId(id),
    index: "$index",
  },
}});

Try another workaround for test reasons:

MySchema.updateMany({ _id: mySchemaId },[{
$addFields: {
  index: "$level",
}},{
$push: {
  referredHierarchy: {
    index: "$index",
  },
}}]);

updateOne doesn't accept pipeline aggregation operators so try with this updateMany for testing.

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!