1

Please see the example:

User Object:

{ 
    name: 'Mike',
    age: 16,
    createdAt: Wed Feb 12 2014 18:06:50 GMT-0600 (CST),
    updatedAt: Wed Feb 12 2014 19:30:54 GMT-0600 (CST),
    id: 7 
}

Pet Objects associated with the user Mike

{
    name: 'Scooby',
    color: 'pink',
    petAge: 2
    id: 1,
    createdAt: Wed Feb 12 2014 18:06:50 GMT-0600 (CST),
    updatedAt: Wed Feb 12 2014 18:06:50 GMT-0600 (CST) 
}

{
    name: 'Alpha',
    color: 'red',
    petAge: 5
    id: 2,
    createdAt: Wed Feb 12 2014 18:16:50 GMT-0600 (CST),
    updatedAt: Wed Feb 12 2014 18:16:50 GMT-0600 (CST) 
}

I want to get sum of 'petAge' for pets of Mike. I was trying the below query, but it did not work.

User.find({name:'Mike'})
.populate('pets')
.sum('pets.petAge')
.exec(function(e,r){

});

I want to understand if getting sum of petAge is possible or not. (sum('pets.petAge')).

BrTkCa
  • 4,703
  • 3
  • 24
  • 45
swapnilagarwal
  • 1,126
  • 8
  • 16

1 Answers1

0

What you can do is use the sum function on the Pets model like this.

Pets.sum('petAge').where({user: "UserID"}).exec(function (e,r) {
//do what you want here
});

here UserID is the id of the user.