Reputation: 6257
I have a messaging app, and a route to fetch a user's messages. A user can have 1000+ threads. I use Mongoose and Express.
I basically find a user by id, populate its messages array, and then apply a reverse() on it so it displays all the threads from new to old. I do it because I don't know how to sort a populated field. Is it fine to use native js instead of mongoose sort method form a performance point of view?
const user = await User.findById({ _id: userId }).populate("messages");
return res.json({ messages: user.messages.reverse() });
If it's crap, how to sort such a populated field?
Upvotes: 0
Views: 132
Reputation: 1560
if you want to sort in order of creation you can use the _id
field of each message. MongoDB treats sorting by _id
the same as sorting by creation time. So your mongoose query would look like:
const user = await User
.findById({ _id: userId })
.populate({path: 'messages', options: { sort: { '_id': -1 } } });
return res.json({ messages: user.messages });
I am not quite sure as to the performance comparison of sorting using JS or Using mongoose though...
Upvotes: 1