mongoose sort by dates from array
<p>I have a <code>Chat</code> model which has a <code>messages</code> array which holds <code>Message</code>s. Each <code>Message</code> has both a <code>dateSent</code> property and a <code>dateViewed</code> property. The <code>Message</code> items are <em>embedded</em>, not <em>referenced</em>.</p>

<p>How can I sort <code>Chat</code>s by most recent <em>not viewed</em> <code>Message</code> (ie, empty <code>dateViewed</code>) first and then by <code>dateSent</code>? (think Facebook Messenger behavior...)</p>

<p>This is what I've tried so far (note that <code>Chat</code> also has a <code>users</code> array):</p>

<pre><code>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
});
</code></pre>

<p>The above does not seem to work, as the <code>Chat</code>s come out in a different order (the same as without <code>sort()</code>). Any thoughts?</p>

<p><strong>EDIT:</strong> The suggested answer didn't help me because I don't want to sort the <code>Message</code> objects in the <code>message</code> array, but rather sort the <code>Chats</code> resulting from the query, by the dates in the <code>Message</code> object they hold in a <code>messages</code> array.</p>