0

I would like to get the number of objects in a Collection and then use that number to perform a find. The code currently looks like this:

function() {
  TestModel.count({}, function(err, num) {
    if (err) {
      return callback(err, undefined);
    }

    options.skip = Math.max(0, Math.floor((num - limit) * Math.random()));
    options.limit = limit;

    TestModel.find(conditions, fields, options).exec(callback);
  });
}

Where testModel is a mongoose model. And this works great! However, I would like to also be able to return the entire query (including count) pre-execution if callback above is null so that users can append more options to the pipeline (e.g. populate). How can I accomplish this?

Larry Price
  • 429
  • 1
  • 4
  • 15
  • What is `_this`? Is it a Mongoose model? – JohnnyHK Oct 07 '14 at 12:54
  • Yes, sorry about that - let me edit the question to make that clearer. – Larry Price Oct 07 '14 at 13:00
  • What do you mean by the "(inlcuding `count`)" part of "return the entire query (including `count`)" pre-execution? Do you mean the `num` result of the `count` query? – JohnnyHK Oct 07 '14 at 13:08
  • Given the above implementation, I need the result from count to run my find query. What I want is to be able to return an executable query from the scope of `function`, so I want to not execute count immediately either (since it's asynchronous). – Larry Price Oct 07 '14 at 13:48
  • I don't see a way to get that to work. Probably better to always use a callback and have the caller use [`Model.populate`](http://mongoosejs.com/docs/api.html#model_Model.populate) to populate references in the result docs as needed. – JohnnyHK Oct 07 '14 at 13:55

0 Answers0