Reputation: 85
I have an application that queries an API and then attempts to store that query in the Mongo document. It seems pretty straightforward from the documentation, but I seem to be missing a step, but I have little idea of what's wrong. Could one of you point me in the right direction? Thanks!
I have a line that selects some records from the DB, then runs a loop querying the API. I run into the error undefined method
[]' for nil:NilClass` when the program reaches the line
EntityMetadata.where(id: c['id'].to_s).add_to_set(:mood, result["mood"])
The console also outputs this: MOPED: 127.0.0.1:27017 COMMAND database=admin command={:ismaster=>1}
, which I have no idea how it got there.
This is the full code if you're interested
puts "Getting sentiment for all entities from Viralheat..."
api_key = '___________------_____-----'
puts "a"
base_uri 'viralheat.com/api/sentiment'
content_sql = 'SELECT content,id FROM entities'
puts content_sql
content = ActiveRecord::Base.connection.select_all(content_sql , "Entity Content")
query = {:api_key => api_key}
asdf = {}
content.each do |c|
puts c["content"]
puts "Getting Sentiment for " + c["content"].to_s
query[:text] = c["content"]
result = self.get('/review.json', :query => query)
puts "asdf"
EntityMetadata.where(id: c['id'].to_s).add_to_set(:mood, result["mood"])
puts "ss"
EntityMetadata.where(id: c['id'].to_s).add_to_set(:prob, result["prob"])
#update_mood_sql = "UPDATE entities SET mood = '#{result["mood"]}' WHERE id ='" + c["id"].to_s + "'"
#update_prob_sql = "UPDATE entities SET probability = '#{result["prob"]}' WHERE id ='" + c["id"].to_s + "'"
#ActiveRecord::Base.connection.update_sql(update_mood_sql, "Updating mood")
#ActiveRecord::Base.connection.update_sql(update_prob_sql, "Updating prob")
end
Here is the model code:
class EntityMetadata
include Mongoid::Document
field :_id, type: Integer
field :fingerprint, type: String
index({ fingerprint: 1 }, { sparse: true })
# TODO: change this to use the entity_id as the :_id field, to save space
# field :entity_id, type: Integer
# index({ entity_id: 1 }, { unique: true })
def entity
@entity ||= Entity.find_by_id(self._id)
end
end
Upvotes: 2
Views: 1866
Reputation: 23648
Purely from the error message I would say that the problem has nothing to do with Mongoid but rather with either c
or result
:
EntityMetadata.where(id: c['id'].to_s).add_to_set(:mood, result["mood"])
If any of these two is not set (nil
) then the statement fails and you never actually reach Mongoid.
Try using pry (pry-rails) and insert a binding.pry
on the line above to inspect these two variables to see if none of them are nil.
Upvotes: 1