Recommendations for a simple MongoDB database structure

I'm just getting started with MongoDB and Mongoid for Rails and need some advice on the proper design of a simple blog database.

I am currently using the structure below, but I need a way to request all comments written by this user (the equivalent of the relational db would be Comment.where('user_id = ?', user_id) ).

Is this set up correctly or do I need to move the comments into my own document and not insert them in the messages (as in the relational db schema)?

Appreciate any advice, thanks.

Database schema

 post { _id: (object id) title: string body: string user_id: reference comments: [ { _id: (object id), body: string, user_id: reference }, { _id: (object id), body: string, user_id: reference }, ... ] } user { _id: (object id) name: string } 

In MongoDB, my respective models are:

 class Post include Mongoid::Document field :title field :body embeds_many :comments references_one :user end class Comment include Mongoid::Document field :body embedded_in :post references_one :user end class User include Mongoid::Document field :name references_many :posts end 
+4
source share
3 answers

There's a great article on Mongodb.org about various comment modeling options.

Check out: http://www.mongodb.org/display/DOCS/MongoDB+Data+Modeling+and+Rails#MongoDBDataModelingandRails-ModelingComments

+3
source

You can use dot-notation in MongoDB to run query filters in embedded documents. In your case, to get all the user comments, you can simply do:

 Post.where("comments.user_id" => myUser.id).all 
+1
source

http://www.mongodb.org/display/DOCS/Dot+Notation+ (Achieve + to + objects)

But not sure how many different options you really need.

Embedded documents or multiple queries or database links are parameters.

Not sure why this needs to be asked again and again.

0
source

Source: https://habr.com/ru/post/1338616/


All Articles