dafne kiyui 🌻<p>oh <a href="https://veganism.social/tags/Mongoose" class="mention hashtag" rel="nofollow noopener noreferrer" target="_blank">#<span>Mongoose</span></a>, we come head-to-head once again 🤌</p><p>> how does the mongo driver maintain the sort order of keys when it is stored as an object?</p><p>it doesn't – and relying on the fact that it may is a bad idea[1]. databases, especially <a href="https://veganism.social/tags/NoSQL" class="mention hashtag" rel="nofollow noopener noreferrer" target="_blank">#<span>NoSQL</span></a> ones, over time begin to look very ugly and fields that once felt aptly named no longer make sense so we rely heavily on aliases. this also makes it easy to transform / rename fields on the <a href="https://veganism.social/tags/GraphQL" class="mention hashtag" rel="nofollow noopener noreferrer" target="_blank">#<span>GraphQL</span></a> level without impacting the database or affecting older applications, but i digress.</p><p>anyhow, TIL or today-i-encountered actually that by using aliases on sort fields (something we had oddly never needed to do before) the `translateAliases` method for Mongoose models does not maintain the order of the object it receives.</p><p>this means `{ a: 1, b: -1, c: 1}` could very well become `{ a: 1, c: 1, B: -1 }` when transformed by this method (where b is an alias of B) and thus breaking the sort order of the application.</p><p>disclaimer: i know this is a matter of code cleanliness vs. what we can or can't do since we could just not use aliases for sorting, but that's extra mental load, y'know? </p><p>[1]: <a href="https://github.com/Automattic/mongoose/issues/4941" rel="nofollow noopener noreferrer" translate="no" target="_blank"><span class="invisible">https://</span><span class="ellipsis">github.com/Automattic/mongoose</span><span class="invisible">/issues/4941</span></a><br>[2]: <a href="https://mongoosejs.com/docs/api/model.html#Model.translateAliases" rel="nofollow noopener noreferrer" translate="no" target="_blank"><span class="invisible">https://</span><span class="ellipsis">mongoosejs.com/docs/api/model.</span><span class="invisible">html#Model.translateAliases</span></a>()</p>