- Tutorials >
- Getting Started (Sinatra)
Getting Started (Sinatra)¶
On this page
New Application¶
This section shows how to create a new Sinatra application using Mongoid for data access. The process is similar for other Ruby applications not using Ruby on Rails.
The complete source code for this application is available in the mongoid-demo GitHub repository.
Create Git Repo¶
While not required, we recommend creating a Git repository for your application:
Commit your changes as you are following this tutorial.
Create Gemfile¶
Create a file named Gemfile
with the following contents:
Install Dependencies¶
Run the following commands to install the dependencies:
This command will generate a file named Gemfile.lock
which we recommend
committing to your Git repository.
Run MongoDB Locally¶
To develop locally with MongoDB, download and install MongoDB.
Once MongoDB is installed and running, create a file named config/mongoid.yml
pointing to your deployment. For example, if you launched a standalone
mongod
on the default port, the following contents would be appropriate:
Use MongoDB Atlas¶
Instead of downloading, installing and running MongoDB locally, you can create a free MongoDB Atlas account and create a free MongoDB cluster in Atlas. Once the cluster is created, follow the instructions in connect to the cluster page to obtain the URI. Use the Ruby driver 2.5 or later format.
Create a file named config/mongoid.yml
with the following
contents, replacing the URI with the actual URI for your cluster:
Basic Application¶
Create a file named app.rb
with the following contents. First, some
requires:
Load the Mongoid configuration file and configure Mongoid. This is done automatically when Mongoid is used with Rails, but since we are using Mongoid with Sinatra, we need to do this ourselves:
Now we can define some models:
… and add some routes:
Existing Application¶
To start using Mongoid in an existing Sinatra applications, the steps are essentially the same as the one given above for a new application:
- Add the
mongoid
dependency to theGemfile
. - Create a
mongoid.yml
configuration file. - Load the configuration file and configure Mongoid in the application.
- Define Mongoid models.