MongoDB 深度探索与实践
1. 嵌入式文档的使用
在构建模型时,我们可以将评论嵌入到书籍模型中。以下是在 Rails 控制台中为书籍添加评论的具体步骤:
1. 找到目标书籍:
b = Book.where(title: "Oliver Twist").first
- 创建评论:
b.reviews.create(comment: "Fast paced book!", username: "Gautam")
b.reviews.create(comment: "Excellent literature", username: "Tom")
- 查看书籍的评论:
b.reviews
查看 MongoDB 中存储的数据,会发现评论被嵌入到了书籍对象中:
db.books.findOne()
{
"_id" : ObjectId("4e86e45efed0eb0be0000010"),
"author_id" : ObjectId("4e86e4b6fed0eb0be0000011"),
"category_ids" : [
ObjectId("4e86
超级会员免费看
订阅专栏 解锁全文
907

被折叠的 条评论
为什么被折叠?



