Mongoose - Take sum of [Number] and add new property to same document
<p>I have the following document in a Mongo database:</p><pre><br /><code>{<br /> _id: 1,<br /> question: "Blue or red?",<br /> __v: 0,<br /> votes: [9, 5]<br />}<br /></code><br /></pre><p>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:</p><pre><br /><code>{<br /> _id: 1,<br /> question: "Blue or red?",<br /> __v: 0,<br /> votes: [9, 5],<br /> totalVotes: 14<br />}<br /></code><br /></pre><p>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.</p><p>This was my "attempt" to do so:</p><pre><br /><code>var getTotal = function(arr){<br /> var total = 0;<br /> for(var i in arr) { total += arr[i]; }<br /> return total;<br /> };<br /><br />Model.update({ $set: { totalVotes: getTotal(votes) }}, function(){<br /> console.log('Updated.');<br />});<br /></code><br /></pre><p>Obviously <code>votes</code> 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 <code>getTotal()</code> function?</p><p>Here's the schema of the Model, btw:</p><pre><br /><code>question: {type: String, required: true},<br />votes: [Number],<br />totalVotes: Number<br /></code><br /></pre><br /><h2>Click here view more answers <a href="%20http://stackoverflow.com/questions/34470352/mongoose-take-sum-of-number-and-add-new-property-to-same-document">http://ift.tt/1QS1Lvi</a></h2>
Nhận xét
Đăng nhận xét