Reputation: 3543
Thanks to Rafael Freitas here is my update function of the mongoDB:
const updated = await db.Mother.update({
"cards.advanced.unit": card.unit
},
[
{
$set: {
"cards.advanced": {
$map: {
input: "$cards.advanced", // I cannot use: ["$cards." + level]
as: "adv",
in: {
_id: "$$adv._id",
unit: "$$adv.unit",
cards: {
$map: {
input: "$$adv.cards",
as: "advcard",
in: {
$cond: [
{
$eq: [
"$$advcard.id",
cardID
]
},
{
type: "this is a NEW updated card",
id: "$$advcard.id"
},
"$$advcard"
]
}
}
}
}
}
}
}
}
],
{
new: true,
})
I just want to be able to dynamically evaluated the level of the query so instead of using :
"cards.advanced.unit"
I can use this:
["cards." + level + ".unit"]
But when it comes to the sting inside the map
:
$map: {
input: "$cards.advanced", // I cannot use: ["$cards." + level]
...
then I cannot use just: ["$cards." + level]
The updated collection properties will be inserted into an array surprisingly!!
How can I dynamically define the level
inside that map
?
Upvotes: 0
Views: 30
Reputation: 707328
Just remove the array brackets.
input: "$cards." + level
This is just string addition (adding two strings together). The array brackets have nothing to do with causing the strings to be added together. That's just something else you needed in your other context.
As an example, you can just add two strings together and it creates a new string with the combined results:
let x = "two";
let result = "one, " + x;
console.log(result);
The brackets would be needed if it was in the left side of the object property declaration. That would be called a computed property name and is a Javascript feature that allows a Javascript expression to be used for the left side of a property declaration. The brackets allow a Javascript expression to be used in this specific place where an expression would not normally be allowed in the language. An expression is always allows on the right had side for the property value so the brackets are not used there. If they were used on the right side, it would be declaring an array.
Upvotes: 1