简体   繁体   English

使用AJAX构造mongodb查询

[英]Construct mongodb query with AJAX

I'm trying to get a count of users with the email example@email.com via the ajax below: 我正尝试通过以下ajax通过电子邮件example@email.com来统计用户数量:

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: 而这在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). 但这不起作用(获取完整用户列表的数量,这让我认为req.body为空)。 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. 您可能不希望仅传递req.body而是获得您发布的参数。 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. 但是可能您的函数存在的问题是您没有传递req

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

Then you need to pass in not only db but req and res as well. 然后,你需要不仅通过db ,但reqres为好。

And though you did not post it in your question, your route definition needs to change. 尽管您没有在问题中发布它,但您的route定义仍需要更改。 Arguments to routes are req and res only as that is what gets passed in: 路由的参数是reqres仅是因为传入的是:

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. 因此,目前您只是获得count ,作为响应中的数字。 Which to this point is what you asked for. 这是您要的。 But that's just a number, it's not JSON. 但这只是一个数字,不是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: 并且您还有一个对象作为要传递的数据。这不是url编码的,请使用$ .param帮助器:

.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. 花一些时间通读文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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