How to design the schema for an author/user model in mongodb
I have looked through most of the mongodb schema design articles on mongo's website and most of the questions here on SO. There is still one use case which I haven't figured out. When looking at these tutorials, they usually reference the article comments problem and the products/categories problem. I want to figure out how to model the one to many relationship (author to posts) when querying a list of posts. Here are the example schemas:
Users: {
_id: ObjectID
Name: String
Email: String
}
Posts: {
_id: ObjectID
user_id: ObjectID
body: String
comments: [
body: String
]
}
Now, lets say you want to run a query for the latest 10 posts. A pretty simple query, but now you have posts with the possibility of each one having a unique ObjectID pointing to the user. Now, how should you accomplish getting the name and email of each user for a post.
Should you create an array of the user ObjectID's from the posts query and then run the query db.users.find({ _id: {$in: PostsUserIDArray}}); After that would you use your application logic to match the right user information to the correct post?
Should you keep a copy of the data in posts. I.E. keep the user ID, name, and email in the posts table. Then just have a hook when a user updates this information to update all the information in posts.
An option which myself or my friend have not thought of.
I appreciate all help as I try to wrap my head around mongo data modeling.
For a few videos I have seen from MongoDB creators, they advocate the second solution. If your user have more data than just a name and email and if you display only name and email when displaying apost, then it's not really bad to store it in the post. Thus you don't have to perform others queries when querying for posts. And since a user doesn't normally change his name every day, it's more effective to run an update to all posts once he changes his name than perform other queries to retrieve informations when displaying posts.
Edit : link to a video http://lacantine.ubicast.eu/videos/3-mongodb-deployment-strategies/
精彩评论