I'm trying to query a collection using aggregate but getting TypeError: users.aggregate is not a function. Here's my code:
./app.js (reduced to fit)
var express = require('express');
var mongo = require('mongodb');
var monk = require('monk');
var db = monk('localhost:27017/mydb');
var users = require('./routes/users');
var app = express();
app.use(function(req, res, next) {
req.db = db;
next();
});
app.use('/users', users);
module.exports = app;
./routes/users.js
var express = require('express');
var router = express.Router();
router.get('/test', function(req, res) {
var users = req.db.get('users');
users.aggregate([{ $match: { username: 'test0' }}], function(err, data) {
res.json(data);
});
});
module.exports = router;
I'm running MongoDB version 3.2.10 and the above query works fine in the console. I've looked up solutions and they all suggest to check the MongoDB version, which I've already done. I've also tried req.db.collection('users').aggregate (as suggested by another post) and receive a similar error: req.db.collection is not a function. What am I missing?
EDIT:
Running users.find({ username: 'test0' }, func... works and returns correct data.
EDIT2: Added more code.
req.db.get? Are you exporting that?aggregateand I must useusers.col.aggregate(). Answered here: stackoverflow.com/questions/23951123/…