Skip to content

Instantly share code, notes, and snippets.

@max-power
Last active October 29, 2017 14:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save max-power/9338766 to your computer and use it in GitHub Desktop.
Save max-power/9338766 to your computer and use it in GitHub Desktop.
Sinatra + MongoDB + JSON
require "sinatra"
require "mongo"
require "json"
class SimpleMongoApi < Sinatra::Base
set :mongo, Mongo::Client.new("mongodb://my.mongo.host/database")
def collection
settings.mongo["things"]
end
def object
collection.find(id_selector(params[:id]))
end
def id_selector(id)
{ _id: BSON::ObjectId.legal?(id) ? BSON::ObjectId.from_string(id.to_s) : id }
end
before do
content_type :json
end
get '/' do
collection.find.limit(params.fetch(:limit, 20).to_i)
end
post '/' do
collection.insert_one params[:thing]
end
get '/:id' do
object.first
end
put '/:id' do
object.find_one_and_replace(params[:thing], return_document: :after)
end
delete '/:id' do
object.find_one_and_delete
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment