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
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:
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:
Cons: