Field/key named "id", different than "_id"?

136 views
Skip to first unread message

Dean Langford

unread,
Mar 5, 2012, 9:17:44 AM3/5/12
to mongo...@googlegroups.com
From what I gather (after reading the documentation, some experimentation and some googling) keys with a name of "id" are not really allowed when using MongoMapper? And that :id is basically a synonym for the "_id" primary key field in a MongoDB collection? Is this correct?

My problem is that I have an existing MongoDB database in which one collection has a non-primary key field name "id", in addition to it's "_id" field.

If my assumption here is correct, is there any way I can use MongoMapper with such a collection? Any workarounds of which I am not aware?

Thanks

Brian Hempel

unread,
Mar 5, 2012, 9:47:03 AM3/5/12
to mongo...@googlegroups.com
You are going to have quite a bit of trouble.

For getting/setting you can skip the id method and get/set the key directly...

my_object[:id]
my_object[:_id]
my_object[:id]  = ObjectId.new()
my_object[:_id] = ObjectId.new()

...but for querying, all your queries on :id will be turned into queries on :_id, so you're out of luck there unless you drop to the driver...

MyClass.collection.find( {:id => "something"}, :transformer => lambda { |doc| MyClass.load(doc) } )

Brian


--
You received this message because you are subscribed to the Google
Groups "MongoMapper" group.
For more options, visit this group at
http://groups.google.com/group/mongomapper?hl=en?hl=en

Jamie Orchard-Hays

unread,
Mar 5, 2012, 10:26:01 AM3/5/12
to mongo...@googlegroups.com
Mongodb stores ids in a special field called "_id". All entries in a collection will have these.

MongoMapper maps _id to id; therein lies your problem. I'd drop into the driver or mongo shell and rename your "id" fields to something else.

Jamie

Sam Bennett

unread,
Oct 17, 2013, 11:15:19 AM10/17/13
to mongo...@googlegroups.com
You are correct about this however, looking into the source code for the gem I found that the if statement for checking that you have used id, if removed fixes the issue. I have created a forked change that allows you to use this. I am just looking at a way to make it flagable.

Chris Heald

unread,
Oct 17, 2013, 1:08:58 PM10/17/13
to mongo...@googlegroups.com
You'll also need to fix the mappings via Normalizers::HashKey in Plucky, as keys are translated there as well.
Reply all
Reply to author
Forward
0 new messages