amnesia
amnesia

Reputation: 1988

How to create a computed field using another computed field in a Mongoose projection?

Consider a schema with the following properties:

{
  maxDmg: Number,
  attacks: Number
}

I need to create a computed field which includes the result from another computed field, something like:

$project {
  maxDmg: true,
  attacks: true,
  effDmg: { $multiply: ["$maxDmg", 0.70] },
  dps: { $divide: [ {$multiply:["$effDmg","$attacks"]}, 60 ] }
}

But it looks like the computed column 'effDmg' cannot be referenced within another computed column. Is there a workaround?

Upvotes: 0

Views: 363

Answers (1)

s7vr
s7vr

Reputation: 75964

I don't think you can access existing computed varible, but you can create the same computed variable using let opertor and use in the another computed varible. Hope this helps.

$project: {
    maxDmg: true,
    attacks: true,
    effDmg: {
        $multiply: ["$maxDmg", 0.70]
    },
    dps: {
        $let: {
            vars: {
                effDmg: {
                    $multiply: ["$maxDmg", 0.70]
                }
            },
            in: {
                $divide: [{
                    $multiply: ["$$effDmg", "$attacks"]
                }, 60]
            }
        }
    }
}

Update:

You can keep the computations inside one project and later you can project them out. This way atleast you end up reusing the variables.

$project: {
    maxDmg: true,
    attacks: true,
    together: {
        $let: {
            vars: {
                effDmg: {
                    $multiply: ["$maxDmg", 0.70]
                }
            },
            in: {
                dps: {
                    $divide: [{
                        $multiply: ["$$effDmg", "$attacks"]
                    }, 60]
                },
                effDmg: "$$effDmg"
            }
        }
    }
}

Sample Output:

{
    "maxDmg": 34,
    "attacks": 45,
    "together": {
        "dps": 17.849999999999998,
        "effDmg": 23.799999999999997
    }
}

Upvotes: 1

Related Questions