Facebook Pixel
API Design With Relationships: Interview Questions

How do you handle relationships in MongoDB?

The answer

Use refs (ObjectId fields with ref) and populate on read. For high-traffic reads, denormalize (copy key fields). For large N (messages, comments), use a separate collection with a ref. For small, tightly coupled data, embed.

More FAQs in API Design With Relationships: Interview Questions

Looping over documents and calling findById for each reference does N+1 queries. Fix: use populate to do it in 2 queries (one for the parent, one for all referenced docs).

Embed for small, tightly coupled data that always loads together (an address in a user). Reference for one-to-many with large N (messages, comments, payments). Embedding large arrays bloats documents; use refs.

Delete related documents in the same handler. Use deleteMany for each related collection, then delete the parent. Do it in a transaction if your MongoDB supports it, so a failure rolls back.

Still have questions?

Browse all our FAQs or reach out to our support team

Want to upskill yourself?

Your learning library

Small steps. Big possibilities.

Find your next course. Build something great.

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.
Please Login.
Please Login.
Please Login.