Mongomapper: does "_id" field conflict with "id"?

983 views Asked by At

I have a collection which contains both _id and id field. When I search by id field in mongo client everything is fine. When I search through mongomapper model like: Product.find_by_id(6) or Product.where(:id => 6) it return empty Plucky object and I can see that it looks for an _id field instead of id.

As I understand mongomapper just always using _id, no matter if you specifically want to find something by id.

Is there any work around for it or I'm doing it wrong?

2

There are 2 answers

0
Crashalot On

It could be caused by this issue (https://github.com/jnunemaker/mongomapper/issues/195) if you ever had an instance with a key of "id." Mongo remembers every key from every instance, unless you clear the key explicitly.

2
Mark Embling On

I believe MongoMapper treats id and _id both equally. id is just a friendlier representation of _id.

In your particular case, is there any reason that you need to have the id field as well? I'd recommend changing that, particularly if there is another more descriptive name which would fit. If you are actually using the id field as a unique identifier (which it sounds like you might be), the best approach would probably be to store it in the _id field instead. As you will already be aware, this is required on all MongoDB documents and can either be specified by you (your application), or added on later by your driver outside of the scope of your application code.

Hope that helps.