Looking to use em-mongo for a text analyzer script which loads text from db, analyzes it, flags keywords and updates the db.
Would love to see some examples of em-mongo in action. Only one I could find was on github em-mongo repo.
   require 'em-mongo'
   EM.run do
     db = EM::Mongo::Connection.new.db('db')
     collection = db.collection('test')
     EM.next_tick do
       doc = {"hello" => "world"}
       id = collection.insert(doc)
       collection.find('_id' => id]) do |res|
         puts res.inspect
         EM.stop
       end
       collection.remove(doc)
     end
   end
                You don't need the next_tick method, that is em-mongo doing for you. Define callbacks, that are executed if the db actions are done. Here is a skeleton:
class NonBlockingFetcher
  include MongoConfig
  def initialize
    configure
    @connection = EM::Mongo::Connection.new(@server, @port)
    @collection = init_collection(@connection)
  end
  def fetch(value)
    mongo_cursor = @collection.find({KEY => value.to_s})
    response = mongo_cursor.defer_as_a
    response.callback do |documents|
      # foo
      # get one document
      doc = documents.first
    end
    response.errback do |err|
      # foo
    end
  end
end
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With