在非Rails环境中通过Mongoid创建MongoDB索引

问题描述

我正在尝试使用MongoDB作为我的数据库来构建基于Roda的(非Rails)API。我安装了Mongoid gem并配置了连接。不幸的是,当我尝试使用rake db:mongoid:create_indexes创建定义的索引时,由于缺少environment,该任务失败了。我应该怎么做/包括在Rakefile中以提供所需的任务?

回溯:

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)

我的Rakefile的相关部分:

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

rake -T输出:

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

解决方法

您需要:

  • 定义一个名为environment的任务,
  • 在此任务中,加载所有模型类。

如何加载模型类取决于您的应用程序。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...