使用 Ruby 侦听插入 MongoDB 中的嵌入文档

Listen for insertion to an embedded document in MongoDB using Ruby

我正在为发出回调的 Restful 应用程序创建一个基于 ruby 的回调侦听器工具,以便我可以访问发出的回调,例如 RequestBin。对于后端,我有 MongoDB,其中我有 1 个主文档,它为每个会话创建一个可重用的存储桶来侦听请求,并且我有一个根据请求填充的嵌入式文档。

class Bin
    include Mongoid::Document
    include Mongoid::Timestamps
    embeds_many :callbacks
    field :bin_id, type: String
end

class Callback
    include Mongoid::Document
    include Mongoid::Timestamps
    embedded_in :bin, :inverse_of => :bins
    field :callback_id, type: Integer
    field :http_method, type: String
    field :params, type: String
    field :headers, type: String
    field :raw_post, type: String
end

我的问题是有没有办法在 MongoDB 中监听回调文档的插入? 我在互联网上四处张望,发现 MongoDB 有所谓的 capped collectionstailable cursors 允许 MongoDB 将数据推送给听众。但对我来说,它不会工作,因为我已经创建了主文档,我必须听嵌入文档的创建。

没有。无法监听 MongoDB.

中的文档更改

搜索 "mongodb triggers" 以了解更多信息。

How to listen for changes to a MongoDB collection?

所以我最后做了以下事情,

  def self.wait_for_callback(bin_id)
    host = ENV['MONGO_RUBY_DRIVER_HOST'] || 'localhost'
    port = ENV['MONGO_RUBY_DRIVER_PORT'] || MongoClient::DEFAULT_PORT

    db = MongoClient.new(host, port).db('mongoid')
    coll = db.collection('bins')
    retries = 0

    res = coll.find("bin_id" => bin_id).to_a.first
    loop do
      if res["callbacks"].nil? && retries < 45
        sleep 5
        puts "Retry: #{retries}"
        retries += 1
        res = coll.find("bin_id" => bin_id).to_a.first
      else
        return res["callbacks"].to_a.first       
      end
    end
    return nil
  rescue Exception => e
    @@success =false
    @@errors << "Error:\n#{e.inspect}"
    if $debug_flag == "debug"
      puts @@errors 
   end
    return nil
  end

但是这里的问题是重复查询。那么有没有更好的方法呢?