Search code examples
rubymongodbmongoidrakeroda

Creating MongoDB indexes via Mongoid in non-Rails environment


I am trying to build a Roda-based (non-Rails) API using MongoDB as my database. I installed Mongoid gem and configured the connection. Unfortunately, when I am trying to create defined indexes using rake db:mongoid:create_indexes, the task fails due to the lack of environment one. What should I do/include in my Rakefile to provide the required task?

Backtrace:

rake aborted!
Don't know how to build task 'environment' (See the list of available tasks with `rake --tasks`)
/home/tomasz/.rvm/gems/ruby-2.7.1/bin/ruby_executable_hooks:24:in `eval'
/home/tomasz/.rvm/gems/ruby-2.7.1/bin/ruby_executable_hooks:24:in `<main>'
Tasks: TOP => db:mongoid:create_indexes
(See full trace by running task with --trace)

Relevant part of my Rakefile:

require 'mongoid'
path = Gem::Specification.find_by_name('mongoid')
load "#{path.gem_dir}/lib/mongoid/railties/database.rake"

rake -T output:

rake db:create_indexes                    # Create indexes specified in Mongoid models
rake db:drop                              # Drops all the collections for the database for the current Rails.env
rake db:mongoid:create_indexes            # Create indexes specified in Mongoid models
rake db:mongoid:drop                      # Drop the database of the default Mongoid client
rake db:mongoid:purge                     # Drop all non-system collections
rake db:mongoid:remove_indexes            # Remove indexes specified in Mongoid models
rake db:mongoid:remove_undefined_indexes  # Remove indexes that exist in the database but are not specified in Mongoid models
rake db:mongoid:shard_collections         # Shard collections with shard keys specified in Mongoid models
rake db:purge                             # Drop all collections except the system collections
rake db:remove_indexes                    # Remove indexes specified in Mongoid models
rake db:reset                             # Delete data and loads the seeds
rake db:seed                              # Load the seed data from db/seeds.rb
rake db:setup                             # Create the database, and initialize with the seed data
rake db:shard_collections                 # Shard collections with shard keys specified in Mongoid models

Solution

  • You need to:

    • Define a task called environment,
    • In this task load all of your model classes.

    How to load your model classes depends on your application.