Reputation: 1680
I am using MongoDb for a blogging website and I have the following object
from mongoengine import connect,Document,StringField,ListField
class Comment(Document):
content = "hi"
class BlogPost(Document):
comments = ListField(StringField())
As shown above, I have a BlogPost object with a comments attribute. I would like this comments attribute to be a list of all the comments associated with that blog post. The list would contain all the Comment objects associated with that BlogPost.
I am just wondering, how can 'put' the comments in the list? Should I put all their id numbers in the list, then initiate the Comment object later?
Thank you in advance.
Upvotes: 0
Views: 76
Reputation: 57202
If you were using a relational database, I would say yes, use a foreign key to reference the comment ID. You might have two tables:
BlogPost - id, post, more attributes...
Comments - id, comment, more attributes...
BlogComments - blogId, commentId - this is a join table that relates the blogs and comments
You can still use references in mongo as shown here http://docs.mongodb.org/manual/tutorial/model-referenced-one-to-many-relationships-between-documents/ and with DBRefs
http://docs.mongodb.org/manual/reference/database-references/.
The NoSQL paradigm is generally to minimize the number of queries and store the data together that will be accessed together. So your mongo document could look like:
BlogPost : {
id: ...,
post: ...,
comments :
[ { commentId: ..., comment: ..., datettime: ... } ]
}
You also should think about how the data will be accessed. Will comments be used in multiple places or just within the blog post? If you have to update the data in multiple places, repeating it may not be the best idea. You should also consider if mongo (or NoSQL in general) is the right solution for your problem.
There's always a tradeoff - hopefully this helps to illustrate some of them for your case.
Upvotes: 2