Created
October 4, 2012 18:58
-
-
Save jslabovitz/3835672 to your computer and use it in GitHub Desktop.
Broken code that should update Mongo document.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
# | |
# This is intended to test Mongo's atomic-update operation. It fails; see below. | |
# | |
require 'mongomatic' | |
class VideoGroup < Mongomatic::Base | |
Mongomatic.db = Mongo::Connection.new.db('mydatabase') | |
end | |
# | |
# first set up a sample database with a video groups with a couple of videos | |
# | |
VideoGroup.drop | |
video_group = VideoGroup.new | |
video_group['videos'] = [ | |
{ | |
'video_id' => 'video1', | |
}, | |
{ | |
'video_id' => 'video2', | |
}, | |
] | |
video_group.insert | |
# | |
# now update just one video in the video group | |
# | |
video_group = VideoGroup.find_one('videos.video_id' => 'video1') or raise "Failed to find video group" | |
video_group.update!({ 'videos.video_id' => 'video1' }, '$set' => { | |
'videos.$.views' => 123, | |
}) | |
#XXX this fails with 'can't append to array using string field name [$]' | |
# | |
# finally check to make sure the video got properly updated | |
# | |
video_group = VideoGroup.find_one('videos.video_id' => 'video1') or raise "Failed to find video group" | |
video = video_group['videos'].find { |v| v['video_id'] == 'video1' } | |
raise "Failed to set video attributes" unless video['views'] == 123 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment