harshs08
harshs08

Reputation: 730

Listen for insertion to an embedded document in MongoDB using Ruby

I'm creating a ruby based tool of callback listeners for Restful applications that emit callbacks, so that I can access the callback emitted out, something like RequestBin. For the backend I have MongoDB where I have 1 main document which creates a reusable bucket per session to listen to requests and I have an embedded document which is populated per request.

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

My question is there a way of to listen for insertion of callback document in MongoDB? I have looked around on internet and found that MongoDB has what is called capped collections and tailable cursors that allows MongoDB to push data to the listeners. But for me it will not work as I have the main document already created and I have to listen to the creation of embedded document.

Upvotes: 1

Views: 222

Answers (2)

harshs08
harshs08

Reputation: 730

So I ended up doing the following,

  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

But here the problem is have do repeated querying. So is there a better way to do this?

Upvotes: 0

maerics
maerics

Reputation: 156662

Nope. There is no way to listen for document changes in MongoDB.

Search for "mongodb triggers" to learn more.

How to listen for changes to a MongoDB collection?

Upvotes: 1

Related Questions