• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

131
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

almost 3 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.

almost 3 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 Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error