希望将em-mongo用于从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
答案 0 :(得分:2)
你不需要next_tick方法,那就是em-mongo为你做的。定义在db操作完成时执行的回调。这是一个骨架:
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