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