Mongoose: filtering query results

I am creating an Express + Mongoose web application where in one of my views I need to show different subsets of objects from the model.

Specifically, I ping Mongo for all documents from the Applications model. Each app can have different attributes: the date is submitted, whether it has reviews (which are embedded documents), whether it has reviews that belong to a registered user, etc.

I am trying to load all applications (which I need) and then also create copies of this array, the content of which is filtered based on the above attributes. So in the end I'll have a hash with arrays like allApps, recentApps, reviewApps, myReviewedApps, etc.

Does Mongoose use a method whereby I can further filter the query result without having to ping the database? Or should I instead run multiple requests asynchronously and then pass that to the view?

controller

  list: function(req, res) {
    Application.find({}).populate('owner').exec(function (err, apps) {
      if (err) console.log(err);
      res.render('applications/list', {
        apps: apps,
        // other subsets of apps here
      });
    })
  },

      

Template

<div class="tab-content">
  <div role="tabpanel" class="tab-pane content-buffer-plus active" id="all">{{> _tableAllApps apps=apps }}</div>
  <div role="tabpanel" class="tab-pane fade content-buffer-plus" id="to-review">{{> _tableToReviewApps apps=apps }}</div>
  <div role="tabpanel" class="tab-pane fade content-buffer-plus" id="your-reviewed">{{> _tableYourReviewedApps apps=apps }}</div>

  <!-- these ones aren't done and I'm not even sure what to od about them yet... -->
  <div role="tabpanel" class="tab-pane fade content-buffer-plus" id="all-reviewed">{{> _tableAllReviewedApps apps=apps }}</div>
  <div role="tabpanel" class="tab-pane fade content-buffer-plus" id="waitlisted">{{> _tableAllApps apps=null }}</div>
  <div role="tabpanel" class="tab-pane fade content-buffer-plus" id="accepted">{{> _tableAllApps apps=null }}</div>
</div>

      

+3


source to share


2 answers


If the subsequent filtering is fairly simple, such as a date interval or a boolean flag, you can query the most general collection with mongoose and do other filtering outside of mongoose. For example, let's say you get allApps via mongoose request, then you can get the latest Apps with a simple filter like this

var recentApps = allApps.filter(function (app) { return (Date.now() - appDate) > threshold; });

      

or for reviewApps



var reviewedApps = allApps.filter(function (app) { return app.isReviewed; });

      

for more complex filtering, although you will have to call mongoose again with a different query

+1


source


You might need to redesign your app model to apply the discriminator or aggregate .



+1


source







All Articles