For example I have models User and Post
User
{
"_id": ObjectId("pretendThisIsAUserObjectId"),
"name": "someUser"
}
Post
{
"_id": ObjectId("pretendThisIsAUserObjectId"),
"title": "blah blah",
"user_id": ObjectId("pretendThisIsAUserObjectId"),
"content": "more blah"
}
User has many posts. So we have user_id stored in Post.
So when we are listing posts for each user, we will have N+1 queries (N posts plus 1 query for user’s name), since we don’t have join in MongoDB.
Can we also store user name in Post, to optimize?
The short answer is yes. You can denormalise your data to whatever extent you feel is appropriate for your particular needs. You could even go as far to storing an entire
Userdocument in eachPost, but that would be a silly amount of duplication.My first inclination, however, would be to consider application-side caching of the username associated with each user ID, rather than trying to include the name in the
Postdocument or querying for it each and every time you want it.If your usernames are unique, you could consider making the username the
_idof yourUserdocument, rather than the standardObjectId. That makes your user IDs even more useful as you no longer need to do additional queries to find the name of each user, because their name is their ID.