I have a Chat
model which has a messages
array which holds Message
s. Each Message
has both a dateSent
property and a dateViewed
property. The Message
items are embedded, not referenced.
How can I sort Chat
s by most recent not viewed Message
(ie, empty dateViewed
) first and then by dateSent
? (think Facebook Messenger behavior...)
This is what I've tried so far (note that Chat
also has a users
array):
Chat.find({users._id: userId}).sort({messages.dateViewed: -1, messages.dateSent: -1}).exec(function(err, chats){
// handle err
// handle no docs found
// handle docs found
});
The above does not seem to work, as the Chat
s come out in a different order (the same as without sort()
). Any thoughts?
EDIT: The suggested answer didn't help me because I don't want to sort the Message
objects in the message
array, but rather sort the Chats
resulting from the query, by the dates in the Message
object they hold in a messages
array.