Virtual Types in MongoDB
Reference
September 19, 2017
Learned another thing that directly applies to my app which is great–virtual types are what you use to store information on your server as a result of the data that’s stored in your database. For example, in my Value App I need a constantly-updated count of the number of times the user has used a thing
in order to calculate its current value. Before learning about virtual types, I thought I would be calling thingArray.length
all the time, or would have to manually increment a usageCount
variable each time there was a new use. Not so! I just need to set a virual type to count however many usages are present whenever it’s time to do the calculation. This following code shows how to set it up. This is declared outside of the model.
UserSchema.virtual("usageCount").get(function() { |
And this is how you can write a Mocha test for it:
const assert = require("assert"); |
Up Next
Debating whether to go to a meetup tomorrow where I might be able to get some help on my double login problem.