希望将 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
最佳答案
你不需要 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
关于ruby-on-rails - em-mongo 的例子?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5405197/