I have the following document in a Mongo database:
{
_id: 1,
question: "Blue or red?",
__v: 0,
votes: [9, 5]
}
I want to, in the back-end, get the total of votes, 14, (because 9 + 5 = 14) and append a new property on that document dynamically. So in the end, it'll look like this:
{
_id: 1,
question: "Blue or red?",
__v: 0,
votes: [9, 5],
totalVotes: 14
}
I researched how to do this, and found words like: Aggregate, unwind, etc. I don't think those will help me because Aggregating in MongoDB is comparing the properties of documents, and I only want to modify the innards of a singular document relative to the properties of itself.
This was my "attempt" to do so:
var getTotal = function(arr){
var total = 0;
for(var i in arr) { total += arr[i]; }
return total;
};
Model.update({ $set: { totalVotes: getTotal(votes) }}, function(){
console.log('Updated.');
});
Obviously votes
is not defined, and this will result in an error. How would I tell it to get the votes from the Model, and pass it in the getTotal()
function?
Here's the schema of the Model, btw:
question: {type: String, required: true},
votes: [Number],
totalVotes: Number