开发者

Advice on Simple MongoDB Database Structure

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

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

Is this the right set up, or should I move comments out into their own document, and not embed them in posts (as I would in a 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 corresponding models are:

class Post
  include Mongoid::Document
  field :title
  field :body
  embeds_many :comments
  references_one :use开发者_如何学Cr
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


There's a great article on Mongodb.org about the various choices for modeling comments.

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


You can use dot-notation in MongoDB to run query filters against embedded documents. In your case, to retrieve all comments by a user, you could simply do:

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


http://www.mongodb.org/display/DOCS/Dot+Notation+(Reaching+into+Objects)

But not sure how many different options you really need.

Embedded docs or multiple queries or database references are options.

Not sure why this must be asked over and over again.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜