I have an "Assignments" MongoDB collection with documents containing a scoring function. I want to store this scoring function in the Assignment document as the scoring logic may change over time as new assignments are created:
Assignment
{
_id: "assignment1",
question: "Number between 1 and 10",
scoringFunction: function (value) { value * 2 }
}
When a user completes an assignment a new document in the "Events" collection is inserted:
Event
{
_id: "event1",
answer: "4",
score: "8"
}
I can insert the above Assignment document into my Assignments collection, however when I attempt to retrieve the scoringFunction
it's no longer a function it's an object.
Some debugging code:
const assignment = Assignments.findOne({ _id: "test" })
console.log(assignment.scoringFunction)
Debugging code output:
Code {
_bsontype: 'Code',
code: 'function (value) { value * 2 }',
scope: undefined
}
How can I decode this object back into a JavaScript function which can be called with parameters to calculate the score?