deeveeABC deeveeABC - 3 months ago 7x
Javascript Question

Add specific values from the same mongoose collection - node js

I have created a collection in mongoose which looks like this:

{ "_id" : ObjectId("5783a416c9"), "text_usage" : "15", "name" : "A1", "__v" : 0 }
{ "_id" : ObjectId("57831216c9"), "text_usage" : "220", "name" : "A2", "__v" : 0 }
{ "_id" : ObjectId("5783a41asd"), "text_usage" : "100", "name" : "A3", "__v" : 0 }

My schema work is like this:

var serverSchema = new Schema({
name: String,
text_usage: String
var myServer = mongoose.model('MyServer', serverchema)

I want to add all the values in the text_usage together and divide by the number of objects in this list - so basically find an average. HOWEVER, my text_usage needs to be stored as a String as it comes from an API call, so would I have to parseString before adding the values together?

So the final results I want i s something like this:

var totalTextCount = 335;
var objectCount = 3;
var average = 111.66

I had a look at aggregate however I am only working with one collection so I dont think this is suitable for me? Any help is appreciated.


Aggregate can't change existing datatype so in this case you should use find and iterate over all data's to get total, count and avg. like:

var totalTextCount = 0, average = 0, objectCount = 0;

MyServer.find().lean().exec(function(err, datas) {
  datas.forEach(function(data) {
    totalTextCount += parseInt(data.text_usage);
    objectCount+= 1;

  average = totalTextCount / objectCount;
  console.log(totalTextCount, objectCount, average);