【问题标题】:Listen for insertion to an embedded document in MongoDB using Ruby使用 Ruby 监听 MongoDB 中嵌入文档的插入
【发布时间】:2015-02-17 19:39:08
【问题描述】:

我正在为发出回调的 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 将数据推送到侦听器。但对我来说,它不起作用,因为我已经创建了主文档,我必须听嵌入文档的创建。

【问题讨论】:

标签: ruby mongodb mongoid


【解决方案1】:

不。 MongoDB 中无法监听文档变化。

搜索“mongodb 触发器”以了解更多信息。

How to listen for changes to a MongoDB collection?

【讨论】:

  • 感谢 maerics 的回复。我查看了您提供的链接,但给出的答案是使用上限集合,在我的情况下,我没有上限集合元素,而且我想听嵌入文档的更改。
  • @harshs08:正确 - 答案是“不,你不能做你想做的事”。
  • 谢谢。我希望有一些方法可以做到这一点,因为一次又一次地查询以检查某些文档是否存在有点昂贵。
【解决方案2】:

所以我最终做了以下,

  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

但这里的问题是重复查询。那么有没有更好的方法来做到这一点?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-08
    • 1970-01-01
    • 2018-08-21
    • 2021-10-04
    相关资源
    最近更新 更多