Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #Stories are embedded docs in a Feed
- class Feed
- include MongoMapper::Document
- many :stories
- end
- class Story
- include MongoMapper::EmbeddedDocument
- key :title, String
- key :posted_by, String
- end
- #create a feed
- feed = Feed.create
- #the standard way to add an embedded doc
- story1 = Story.new(:title => "Coding", :posted_by => "Michael")
- feed.stories << story1
- feed.save! #this saves the entire feed document
- #atomically add an embedded doc
- story2 = Story.new(:title => "Eating", :posted_by => "Josh")
- Feed.push(feed.id, :stories => story2.to_mongo)
- ## adds this story to the feed
- #you can also do it this way if you already have the feed
- story3 = Story.new(:title => "Sleeping", :posted_by => "Josh")
- feed.push(:stories => story3.to_mongo)
- #atomically remove an embedded doc
- Feed.pull(feed.id, {:stories => {:posted_by => "Josh"}})
- ## removes all stories posted by Josh
- #atomically edit an embedded doc
- Feed.set({:_id => feed.id, "stories.title" => "Coding"}, "stories.$.title" => "Hacking")
- ## edits the title of the FIRST story with a title of "Coding" to "Hacking"
- ## notice the "dot" notation for getting to fields
- ## and the position element ("$"), which returns the *FIRST* of the documents returned in the query
- ## this example makes sense for manipulating single embedded documents, but to update multiple ones
- ## it probably makes more sense to use Ruby Array/Enumerable and save the whole document
- ## I've just been fiddling with this for the past day or so, so if I'm doing something wrong
- ## (or if there's a better way to do some of this stuff), please let me know!
Add Comment
Please, Sign In to add comment