【发布时间】:2011-06-22 04:33:55
【问题描述】:
我刚刚开始使用 MongoDB 和 Mongoid for Rails,需要一些关于设计简单博客数据库的正确方法的建议。
我目前正在使用下面的结构,但我需要一种方法来查询给定用户编写的所有 cmets(关系数据库等效项为 Comment.where('user_id = ?', user_id))。
这是正确的设置,还是我应该将 cmets 移到他们自己的文档中,而不是将它们嵌入到帖子中(就像我在关系数据库模式中那样)?
感谢任何建议,谢谢。
数据库架构
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
}
在MongoDB中,我对应的模型是:
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
【问题讨论】:
-
一旦我发布了这个,StackOverflow 抛出了this related post,它提供了一个很好的答案。不过,就更好的方法获得意见仍然是件好事。
标签: ruby-on-rails mongodb database-design mongoid nosql