diff --git a/app/imports/api/engine/computation/writeComputation/writeScope.js b/app/imports/api/engine/computation/writeComputation/writeScope.js index 6d0aecbc..3bb550f8 100644 --- a/app/imports/api/engine/computation/writeComputation/writeScope.js +++ b/app/imports/api/engine/computation/writeComputation/writeScope.js @@ -4,7 +4,8 @@ import { EJSON } from 'meteor/ejson'; export default function writeScope(creatureId, computation) { const scope = computation.scope; const variables = computation.creature?.variables || {}; - let $set; + let $set, $unset; + for (const key in scope){ // Remove large properties that aren't likely to be accessed delete scope[key].parent; @@ -24,7 +25,16 @@ export default function writeScope(creatureId, computation) { $set[`variables.${key}`] = scope[key]; } } - if ($set) { - Creatures.update(creatureId, {$set}); + + // Remove all the keys that no longer exist in scope + for (const key in variables) { + if (!scope[key]) { + if (!$unset) $unset = {}; + $unset[`variables.${key}`] = 1; + } + } + + if ($set || $unset) { + Creatures.update(creatureId, {$set, $unset}); } }