5

希望将 em-mongo 用于文本分析器脚本,该脚本从 db 加载文本、分析它、标记关键字并更新 db。

很想看到一些 em-mongo 的例子。我只能在 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
4

1 回答 1

2

你不需要 next_tick 方法,那是 em-mongo 为你做的。定义回调,如果数据库操作完成则执行。这是一个骨架:

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
于 2012-04-24T12:58:51.847 回答