0

I wanted to use integer values for ID, so i updated my model to this:

class Word
  include Mongoid::Document

  field :id,           type: Integer
  field :name,         type: String

  before_create :assign_id

  private

  def assign_id
    self.id = Word.count.to_i + 1
  end

end

Only downside, that i can think of, is that i have to make sure i handle deletion correctly. So any other tables, that have this id, gets updated, on destroy. But other than that it works, but could there be any problems, by doing this?

PragmaticEd
  • 505
  • 1
  • 4
  • 14
  • yes to make it short.. if you do so you might not have an unique key to look up for as _id .in mongo we dont have any primary key except _id until we set a data to unique value – Vignesh Oct 04 '17 at 11:44

1 Answers1

1

It is not advisable to play around with the _id attribute of mongodb, essentially because this has more information than what we presume which include the time of creation, host etc as a hash, and of course this is indexed by default. for more information you can see :

https://docs.mongodb.com/manual/reference/bson-types/#objectid

We can of course have another attribute in our json document which we can use as a sequence of integers. Though there is no restriction as such on overriding the system generated hash for _id.

vaibhav
  • 3,929
  • 8
  • 45
  • 81