Guest User

Untitled

a guest
Jun 20th, 2018
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.56 KB | None | 0 0
  1. #Stories are embedded docs in a Feed
  2.  
  3. class Feed
  4. include MongoMapper::Document
  5. many :stories
  6. end
  7.  
  8. class Story
  9. include MongoMapper::EmbeddedDocument
  10. key :title, String
  11. key :posted_by, String
  12. end
  13.  
  14. #create a feed
  15. feed = Feed.create
  16.  
  17. #the standard way to add an embedded doc
  18. story1 = Story.new(:title => "Coding", :posted_by => "Michael")
  19. feed.stories << story1
  20. feed.save! #this saves the entire feed document
  21.  
  22. #atomically add an embedded doc
  23. story2 = Story.new(:title => "Eating", :posted_by => "Josh")
  24. Feed.push(feed.id, :stories => story2.to_mongo)
  25. ## adds this story to the feed
  26.  
  27. #you can also do it this way if you already have the feed
  28. story3 = Story.new(:title => "Sleeping", :posted_by => "Josh")
  29. feed.push(:stories => story3.to_mongo)
  30.  
  31. #atomically remove an embedded doc
  32. Feed.pull(feed.id, {:stories => {:posted_by => "Josh"}})
  33. ## removes all stories posted by Josh
  34.  
  35. #atomically edit an embedded doc
  36. Feed.set({:_id => feed.id, "stories.title" => "Coding"}, "stories.$.title" => "Hacking")
  37. ## edits the title of the FIRST story with a title of "Coding" to "Hacking"
  38. ## notice the "dot" notation for getting to fields
  39. ## and the position element ("$"), which returns the *FIRST* of the documents returned in the query
  40.  
  41. ## this example makes sense for manipulating single embedded documents, but to update multiple ones
  42. ## it probably makes more sense to use Ruby Array/Enumerable and save the whole document
  43.  
  44. ## I've just been fiddling with this for the past day or so, so if I'm doing something wrong
  45. ## (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