简体   繁体   中英

Mongodb with Mongoose time out when no record exists

I'm making a count query to a mongodb using Mongoose, like this:

Question.count({$and: [{"tags.text": query},{"tags.text": "Diagram"}]}).execAsync()
        .then(respondWithResult(res))
        .catch(handleError(res));

I need to count how much records have the "Diagram" tag and another one I'm getting via parameter.

It works ok when the result is greater than 0, but it just makes a time out with no response if no records are selected. I tried the same query using CLI and it works like charm:

> db.questions.find({$and: [{"tags.text": "Diagram"}, {"tags.text": "tag3"} ]}).count()
0

Any thoughts? I am totally desperate.

** EDIT **

I tried several things and the problem is in the respondWithResult function.

function respondWithResult(res, statusCode) {
  statusCode = statusCode || 200;
  return function(entity) {
    if(entity) {
      return res.status(statusCode).json(entity);
    }
    return null;
  };
}

There is where the time out happens. Only with count, with a find function it works right.

You need to send a response when count is zero, otherwise response will wait until it is timed-out which is happening in your case.

function respondWithResult(res, statusCode) {
  statusCode = statusCode || 200;
  return function(entity) {
    if(entity) {
      return res.status(statusCode).json(entity);
    }
    return res.status(200).json(0); //return 0 as count
  };
}

or simply:

function respondWithResult(res, statusCode) {
      statusCode = statusCode || 200;
      return function(entity) {
          return res.status(statusCode).json(entity);
      };
    }

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