Mongo ids leads to scary URLs Mongo ids leads to scary URLs mongodb mongodb

Mongo ids leads to scary URLs


You can create a composite key in mongoid to replace the default id using the key macro:

class Person  include Mongoid::Document  field :first_name  field :last_name  key :first_name, :last_nameendperson = Person.new(:first_name => "Syd", :last_name => "Vicious")person.id # returns "syd-vicious"

If you don't like this way to do it, check this gem: https://github.com/hakanensari/mongoid-slug


Define a friendly unique field (like a slug) on your collection, index it, on your model, define to_param to return it:

def to_param  slugend

Then in your finders, find by slug rather than ID:

@post = Post.where(:slug => params[:id].to_s).first

This will let you treat slugs as your effective PK for the purposes of resource interaction, and they're a lot prettier.


Unfortunately, the key macro has been removed from mongo. For custom ids,users must now override the _id field.

class Band  include Mongoid::Document  field :_id, type: String, default: ->{ name }end