tsurantino
tsurantino

Reputation: 1027

Mongoose: Filtering query results

I am building an Express + Mongoose web app, where, in one of my views, I need to show different subsets of objects from a model.

Specifically, I ping Mongo for all documents from the Applications model. Each application can have different attributes: date submitted, does it have reviews (which are embedded documents), does it have reviews which belong to the currently logged in user, etc.

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

Does Mongoose a method by which I can further filter a query result without having to ping the database? Or should I instead run multiple queries 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>

Upvotes: 4

Views: 5439

Answers (2)

hankchiutw
hankchiutw

Reputation: 1662

Maybe you should redesign your Application model to apply discriminator or aggregate features.

Upvotes: 2

gabesoft
gabesoft

Reputation: 1228

If the subsequent filtering is fairly simple, such as a date interval, or boolean flag you could query the most generic collection via mongoose and do the other filtering outside mongoose. For example let's say you get allApps via a mongoose query, then you could get the recentApps with a simple filter like so

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

or for reviewedApps

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

for more complex filtering though you'd have to call mongoose again with a different query

Upvotes: 1

Related Questions