MongoDB one-to-many - array of IDs or ID ref on child model? [closed] MongoDB one-to-many - array of IDs or ID ref on child model? [closed] mongoose mongoose

MongoDB one-to-many - array of IDs or ID ref on child model? [closed]


Writes for updates are actually pretty expensive. Inserting a new document is fast, but updating takes some time because you perform a read and a write. If O(r) is time complexity for "read" and O(w) is time complexity for "write", then update is O(r+w). Reads are also actually incredibly efficient if you have an index built on the field(s) you're querying, anyway, so it's generally not something you need to be concerned about. The general advice to follow is to keep your updates to a minimum, whereas reads and inserts are fine, although none of those operations are really a problem as long as your indexing is good.

That aside, I don't recommend denormalizing your Messages into the Chat document. Documents are limited to a 16MB size cap, so if the chat gets particularly large, then MongoDB won't be able to handle it. Even if it never exceeds that limit, you can't optimize the message retrieval--any time you want to load the chat, you need to grab all of the messages at once, but in most realistic scenarios you only need to retrieve e.g. the last few dozen messages and load more as needed! Additionally, keeping your messages as separate documents will allow you to do other helpful tasks, like searching for and displaying only the messages a specific person has sent, skipping to certain points of time, purging all documents older than a given date, creating a TTL index to auto-delete older messages, etc.

So, in terms of potential functionality, performance, document size limitations, and even just ease of management, having separate Message documents with parent references to their corresponding Chat is the preferred method.