1

I'm making an app where users record the number of hours they slept, their eating habits, etc, which gets stored in a collection called Journal.

When the user clicks "stats", it triggers a function called find() which finds all the journal entires a user has submitted and console logs them.

This is what I have so far:

exports.stats = function(req, res) {

    function find() {
        Journal.findOne({'user': req.params.id}, 'sleep', function(err, journal){
            if(err) throw err;
            console.log(journal.sleep);    
        });
    }
    find();
}

In this example, I'm trying to console log the number of hours of sleep of a particular user, however, it only displays the number of hours of sleep of that session, and not ALL of the number of hours of sleep they have recorded

  • Your "function `find()` does not accept and return a "callback" or other resolvable response ( ie Promse ). Unless you do that then your execution will not work how you are expecting it to. That said simply use the built in [`.find()`](http://mongoosejs.com/docs/api.html#model_Model.find) which returns an "array" of "multiple" responses. – Neil Lunn Oct 30 '17 at 02:55
  • @NeilLunn Can you help me out with the syntax? I'm pretty new to mongodb and mongoose so I'm not sure how I'd return that – Marvin Gaye Oct 30 '17 at 02:59
  • As far as I can see , the answer already given shows you the syntax. It also avoids the callback execution problem you have with trying to "wrap" an async call incorrectly. So there is that, and the linked question and answers with multiple approaches, and the basic documentation which is full of examples. – Neil Lunn Oct 30 '17 at 03:02

1 Answers1

0

You should use .find() instead of .findOne()

findOne means only 1 Record

fineOne Documentation - http://mongoosejs.com/docs/api.html#query_Query-findOne

Something like this:

Journal.find( { 'user': req.params.id }, function(err, journal){...})
Ryan Wu
  • 5,963
  • 2
  • 36
  • 47