chovy
chovy

Reputation: 75656

ordering results using mongoose in express

I'm using mongoose to create and model my document schemas.

I have a user_id attribute on a bunch of different schemas, along with a created_at date attribute on them.

I want to generate a list, ordered by created_at date for display as a feed of recent activity on the user's homepage.

How would I query several different models, and then order these items into an array that I can then pass to my ejs view?

Upvotes: 0

Views: 2857

Answers (1)

zemirco
zemirco

Reputation: 16395

You can sort your mongoose query using the sort function. Here are two examples:

query.sort({ field: 'asc', test: -1 });

or

Person
  .find({user_id: 123456})
  .sort('-created_at')
  .exec(function(err, person) {
    // push these results to your array and start another query on a different schema
  });

Upvotes: 2

Related Questions