b2norma
b2norma

Reputation: 45

Need help querying MongoDB with nodeJS. Getting undefined is not a function on the following code

The following code is giving me undefined is not a function on aggregate. My database has 22 numbers in it and I want to get the average. What am I doing wrong?

router.get('/mean', function(req, res) {
        var db = req.db;
        var collection = db.get('numbercollection');
        collection.aggregate([
        {$group : {_id : null, 
                   mean : {$avg : "$number"}
                  }   
        }], function(err, result) {
            console.log(result);
    });
    });

Just let me know if you need more information. Thanks.

Upvotes: 0

Views: 85

Answers (2)

Vignesh
Vignesh

Reputation: 1212

The problem is you have used db.get(collection name) ,whereas it should be db.collection(collection name).

router.get('/mean', function(req, res) {
   var db = req.db;
    var collection = db.collection('numbercollection');
    collection.aggregate([
    {$group : {_id : null, 
               mean : {$avg : "$number"}
              }   
    }], function(err, result) {
        console.log(result);
});
});

Upvotes: 1

Mayuresh
Mayuresh

Reputation: 1

If you are using mongose to connect to mongodb, then mongose doesn't directly support aggregate.

Try using

collection.col.aggregate([ *your query here* ])

something used here

Upvotes: 0

Related Questions