Answer the question
In order to leave comments, you need to log in
How to sort users by latest post in mongoose,nodejs database?
There are 2 collections.
messanges
authorId
to (to whom - I always admin)
createdAt
text
users
_id
avatarURL
name
using mongoose.
The task on sense costs like simple.
Sort the list of users who wrote last, and give information about them.
1. I sorted the posts by date to see the latest posts
2. I grouped the users by their ID to remove duplicates - thus getting a list of users
who wrote last.
3. since I didn’t manage to somehow Join (populate) in the code, I twisted information about users in a loop.
4. Whether it is possible to display the last message from sorting in the same request, otherwise I have to send the request to the database again.
Is my logic of selecting and sorting from the database correct - because sometimes it sorts messages in different ways.
How can I competently make a choice all the time with the help of aggregate, choice and join?
(I could not do any lookup - it seems the information is simple)
There may be idiotic code - I write on nodejs not so long ago
сonst mess = await Message
.aggregate(
[
{ "$match": { "to": 'admin' } },
{ "$sort": { "createdAt" : 1 } },
{ "$group": {"_id": {"authorId": "$authorId",}}}
])
//SEARCH USER BY MESS ID AFTER SORT
let allusers = new Array();
let n=0;
for (const item of mess) {
users0 = await Users.find({_id: item._id.authorId});
allusers.push(users0.map(u => u.toDTO()));
}
res.render('_ajax/messanges', {messusers: allusers})
messusers = await Message
.find({to: 'admin'})
.sort({createdAt: 'asc'})
.distinct('authorId')
.populate({ path: 'authorId', select: 'avatarURL name' })
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question