Facebook Pixel

When should I embed vs reference data in MongoDB?

Embed small, tightly coupled data, like an address on a user. Reference large or shared data, like messages in a chat, to avoid duplication and keep documents small. Embedding is for things always read with the parent; referencing is for shared or growing data.

Verify This Answer

Cross-check this information using these trusted sources:

More FAQs in How to Design MongoDB Schemas for a DevTinder-like React Project

Start with the queries you will run, define User, Connection, and Message schemas with references between them, embed small tightly coupled data and reference shared data, and add indexes on fields you query often like email and user id.

Fields like name, email (unique and indexed), hashed password, bio, skills, and a list of connections. The email must be unique and indexed so login queries are fast and emails are not duplicated.

Use references, which are ObjectIds pointing to other documents. Use populate to fetch the related document when you need the full data. For example, a Message references its sender by id, and you populate the sender to get the user object.

Still have questions?

Browse all our FAQs or reach out to our support team

Want to upskill yourself?

Our courses are taking a Coffee break, but your curiosity shouldn't. Stay engaged with namastedev linkedin, youtube, discord and other resources while you wait.

0
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.