AJ Naidas
AJ Naidas

Reputation: 1424

Merge Mongoose results

I have this Mongoose Query result:

[ { _id: 523ab1be60239c8120000001,
    posts: 
     [ { _id: 523ab1be60239c8120000002,
         creator: 523ab1be60239c8120000001,
         listingType: 'lease',
         title: 'My Second Listing - Made By Person 1',
         __v: 0 } ] },
  { _id: 523ab1e224bfaea520000001,
    posts: 
     [ { _id: 523ab1e224bfaea520000002,
         creator: 523ab1e224bfaea520000001,
         listingType: 'lease',
         title: 'My Second Listing - Made By Person 2',
         __v: 0 },
       { _id: 523ab865ae55497d27000001,
         creator: 523ab1e224bfaea520000001,
         listingType: 'free',
         title: 'My Third Listing - Made By Person 2',
         __v: 0 } ] } ]

I want to be able to store all posts in one array or object so that I can sort them by their _id (timestamp) and display them to the user much easier.

Any ideas on how to achieve this? I'm thinking about doing a loop on each posts and execute a sorting algorithm of some sort to achieve this but just by the word "loop", it already sounds inefficient.

Upvotes: 0

Views: 1015

Answers (1)

sfritter
sfritter

Reputation: 891

If you wanted to sort the documents themselves, I would say to use MongoDB's sort() function. However, since you want to extract a part of the documents, combine them into one object, and sort, there are a few options, and I'm not sure which will perform best.

If you keep your query the way it is, then you really only have the choice of sorting on the application side using a loop of some sort.

Probably, the cleanest way to do this would be to use the aggregation framework. Depending on what your original query was, you can probably transform it into a $match operation and use it first in your pipeline. Then, you should be able to $unwind the 'posts' array, $sort by timestamp, and $group them back together into a single array.

Upvotes: 1

Related Questions