Sum of values Nodejs + Mongoose

1

I need to sum the values stored in a variable in the database.

I have a form and I want to know the total value generated in a variable.

Then I did the following:

               _.each(cliente.data, function (data) {
                  for(i=0; i>=cliente.data.length; i++){
                    var valor= data.valor;

                  }
                });

While i > = visit.oppEY.length (my vector) I must add the values accumulated in the value variable.

But I have tried in several ways and the only thing that happens is the incrementing of values.

    
asked by anonymous 01.09.2015 / 14:45

1 answer

5

I believe you want something like this:

var valor = 0;
_.each(cliente.data, function (data) {
    valor+= Number(data.valor);
});

You are already iterating over cliente.data , you would not need another loop ( for ) within each . Also, you are re-declaring the valor variable within the loop at each iteration, which will prevent you from adding the value to it. Declaring out of the loop the value holds.

In fact, the condition of your for should be i <= cliente.data.length and not i >= cliente.data.length , since i started in 0 will always be less than your array if there is data in it.

    
01.09.2015 / 14:49