Custom Sorting in Mongoose

161 views Asked by At

I have the following schema of story:

story : {
  content: string,
  seenBy: Types.ObjectId[]
}

here seenBy is the array of users,

Now I have a list of stories and I want to sort the list based on the unseen story first and seen at last for a particular logged-in user,

means if the logged-in userid is 2 then story which has the particular userid in seenBy should come last and the other should come ahead.

I am not getting an idea of how to do it.

In the API I have logged in userid,

I have tried the following but it gives compile time error:

 const totalStories = await this.Story.find({})
      .populate(this.populateStory())
      .sort({ seenBy: (val) => {
          return val.includes(userid) ? -1 : 1
       }, updatedAt: 'desc' });

I searched many places but I did not get anything related to my problem statement.

Thank you in advanced

1

There are 1 answers

0
Vats Patel On

After some research, I have come up with a solution,

Using the aggregate function a field can be added to the document temporarily and we can sort on that field as below:

const totalStories = await this.Story.aggregate([
  {
    $addFields: {
      seen: { $in: [authUser.id, '$seenBy'] },
    },
  },
]).sort({ seen: 'asc', updatedAt: 'desc' });

By this we can sort with any custom logic as the field seen will be boolean based on the data in the documents.

I got the idea from the below link: MongoDB ($addField)

Props:

  1. You can write your custom logic (condition) and sort accordingly.
  2. As it is a query so will give optimistic complexity rather than a sort() function on an array.

Cons:

  1. Can't able to populate() because of aggregate (Note: As an alternate, you can use $lookup (work as a join) to populate data MongoDB ($lookup)