0

I have a table like the following

{ _id: 55db87ed69090a5e4b5515cf,
    firstname: 'Bilbo ',
    lastname: 'Baggins',
    email: '[email protected]',
    points: 0,
    password: '$2a$05$o90atG0rfXQN5X7CLFa59e8QO1PcOcFvH47MXDxVmr2E3id7cSEIG',
    __v: 0 } 

When I run this I get all the results

  User.find({points: req.params.points}, function (err, docs) {
        console.log(docs);
    });

How can I fetch all of the records with the points field? I want to be able to fetch all points of every user and count them up.

I am quite new to mongodb/mongoose and having trouble understanding it.

1 Answer 1

1

You can do something like this:

User.find({points: {$exists: true}}, function(err, docs) {
    var count = 0;
    for(var i = 0; i<docs.length; i++) {
        count += docs[i].points;
    }
    console.log('The total of points is: ', count);
});

The {points: {$exists: true}} query will return only the documents that have that field defined.

Sign up to request clarification or add additional context in comments.

2 Comments

Thankyou that worked great! I changed int for var though so it would run.
Oops, I mix languages from time to time. :) I just edited the answer with that correction.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.