简体   繁体   中英

Construct mongodb query with AJAX

I'm trying to get a count of users with the email example@email.com via the ajax below:

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

var queryCount = {
    email:'example@email.com'
}

$.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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM