开发者

Defining a different primary key in Mongomapper

开发者 https://www.devze.com 2023-01-28 11:09 出处:网络
I am defining a primary key in MongoMapper. class B key :_id, string key :externalId, string end The problem is that everything i add a new record in B, it appears that I need to explicity specify

I am defining a primary key in MongoMapper.

class B
  key :_id, string
  key :externalId, string
end

The problem is that everything i add a new record in B, it appears that I need to explicity specify the _id, when it is already defined in the external id

B.new(:_id=>"123", :external_id=>"123 )

That does not quite make sense. There should be a way to specify externalId as the primary key,开发者_开发问答 no?


If your problem is with BSON::ObjectId, I created a plugin that can help you, this plugin adds auto incremented id for MongoMapper documents

https://github.com/phstc/mongomapper_id2

movie = Movie.create(:title => 'The Simpsons Movie')
movie.id # BSON::ObjectId('4d1d150d30f2246bc6000001')
# Here is the mongomapper_id2
movie.id2 # 1

movie2 = Movie.create(:title => 'Pirates of Silicon Valley')
movie2.id2 # 2


I would not try to define the primary key using mongomapper -- it will auto create the _id for you. I do not recommend trying to change this behavior.

class B
  include MongoMapper::Document
  key :your_alternate_id, String, :index=>true
end

B.new.id
#4cf86bf1de2f8970ea000179

B.find("4cf86bf1de2f8970ea000179")

I do not believe you can create your own PK, composite or otherwise.

0

精彩评论

暂无评论...
验证码 换一张
取 消