MongoMapper gotchas

mongomapper mongodb gotchas

12|01|2009

MongoMapper recently has did a restructuring of the API such that foreign keys that previously worked will suddenly be broken. An example.

class User
  include MongoMapper::Document
  
  many :events
end

class Event
  include MongoMapper::Document

  key :user_id, String
end

This used to be the usual way of doing foreign key mapping. But with the advent of Mongo::ObjectID, you have to do either one of 2 things:

  1. Explicitly define the primary key of your user to be a String
  2. Change the type of your user_id to be that of Mongo::ObjectID

Explicitly defining the primary key of your user

class User
  include MongoMapper::Document

  key :_id, String
end

Change the type of your user_id column

class Event
  include MongoMapper::Document
  
  key :user_id, Mongo::ObjectID
end

This will remove all breakages from your specs / tests, assuming you are testing.

blog comments powered by Disqus