Allen
Allen

Reputation: 3771

Construct mongodb query with AJAX

I'm trying to get a count of users with the email [email protected] via the ajax below:

function getCount(event) {
event.preventDefault();

var queryCount = {
    email:'[email protected]'
}

$.ajax({
    type: 'GET',
    data: queryCount,
    url: '/countuser',
    dataType: 'JSON'
}).done(function(response) {
    //Check for successful (blank) response
    if(response.msg === '') {

    } else {

    }
});
}

and this in users.js:

exports.countuser = function(db) {
return function(req, res) {
    db.collection('userlist').find(req.body).count(function(err,count) {
      res.send(count);
    });
  }
};

but this isn't working (getting the count of the complete user list, which makes me think that req.body is empty). What would be a correct way of going about this?

Upvotes: 0

Views: 1436

Answers (1)

Neil Lunn
Neil Lunn

Reputation: 151112

You probably don't want to pass in just req.body but get the param that you posted. But this might be okay as long as you have set up the body parser. There is a better invocation of this but

app.use(express.bodyParser());

But probably your problem with your function is you are not passing req in.

exports.countuser = function(db,req,res) {

Then you need to pass in not only db but req and res as well.

And though you did not post it in your question, your route definition needs to change. Arguments to routes are req and res only as that is what gets passed in:

app.get('/countuser',function(req,res) {

    user.countuser(db,req,res);

So at the moment you are just getting the count, as a number in the response. Which to this point is what you asked for. But that's just a number, it's not JSON. So you need to change a bit.

var countResponse = {};

countResponse.count = count;
res.body(countResponse);

And you also have an object as the data you are passing in. This is not url encoded, use the $.param helper:

.ajax({
    type: 'GET',
    data: $.param(queryCount),
    url: '/countuser',
    dataType: 'JSON'
}).done(function(response) {

In short there are lot of things wrong here. Take some time and read through the documentation.

Upvotes: 1

Related Questions