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 :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