joao_viccari
joao_viccari

Reputation: 1

Mongoid: uninitialized constant (NameError)

I'm currently trying to write a very basic portion of code that reads a ruby file and instantiate some documents into my local MongoDB.

The class modeling my Mongo document is in a separate file called 'search_term.rb', as follows:

class SearchTerm
  include Mongoid::Document
  field :search_term, type: String
end

In a separate file called 'populate_database.rb' that resides in the same folder as 'search_term.rb', I'm trying to read from a list and create new documents and look into my MongoDB Compass if they are actually being created:

require_relative 'search_term'

business_list = [
  'business name 1',
  'business name 2',
  'business name 3',
  'business name 4',
]

for business in business_list
  s_term = SearchTerm.new()
  s_term.search_term = business
  s_term.post
end

The problem is: when I run 'ruby populate_database.rb' I'm getting the error:

<class:SearchTerm>': uninitialized constant SearchTerm::Mongoid (NameError)

I have already tried creating an empty Gemfile and writing:

gem 'mongo'
gem 'mongoid'

into them and running 'bundle install'. After that the following Gemfile.lock file is created:

GEM
  specs:
    activemodel (6.1.4.1)
      activesupport (= 6.1.4.1)
    activesupport (6.1.4.1)
      concurrent-ruby (~> 1.0, >= 1.0.2)
      i18n (>= 1.6, < 2)
      minitest (>= 5.1)
      tzinfo (~> 2.0)
      zeitwerk (~> 2.3)
    bson (4.12.1)
    concurrent-ruby (1.1.9)
    i18n (1.8.10)
      concurrent-ruby (~> 1.0)
    minitest (5.14.4)
    mongo (2.13.0)
      bson (>= 4.8.2, < 5.0.0)
    mongoid (7.3.2)
      activemodel (>= 5.1, < 6.2)
      mongo (>= 2.10.5, < 3.0.0)
      ruby2_keywords (~> 0.0.5)
    ruby2_keywords (0.0.5)
    tzinfo (2.0.4)
      concurrent-ruby (~> 1.0)
    zeitwerk (2.4.2)

PLATFORMS
  x64-mingw32

DEPENDENCIES
  mongo
  mongoid

BUNDLED WITH
   2.2.27

But the problem still persists. Can you guys give me some advice on how to solve this one?

Thanks in advance!!

Upvotes: 0

Views: 1036

Answers (1)

D. SM
D. SM

Reputation: 14530

If you are not using Rails, you need to require "mongoid" yourself somewhere in your application and then load Mongoid configuration. See here for an example of how to do that.

Upvotes: 1

Related Questions