@@ -804,19 +804,58 @@ To define the field anyway, use the ``overwrite: true`` option:
804804 end
805805
806806
807+ .. _custom-id:
808+
807809Custom Ids
808810----------
809811
810- For cases when you do not want to have ``BSON::ObjectId`` ids, you can override Mongoid's
811- ``_id`` field and set them to whatever you like.
812+ By default, Mongoid defines the ``_id`` field on documents to contain a
813+ ``BSON::ObjcetId`` value which is automatically generated by Mongoid.
814+
815+ It is possible to replace the ``_id`` field definition to change the type
816+ of the ``_id`` values or have different default values:
812817
813818.. code-block:: ruby
814819
815- class Band
816- include Mongoid::Document
817- field :name, type: String
818- field :_id, type: String, default: ->{ name }
819- end
820+ class Band
821+ include Mongoid::Document
822+ field :name, type: String
823+ field :_id, type: String, default: ->{ name }
824+ end
825+
826+ It is possible to omit the default entirely:
827+
828+ .. code-block:: ruby
829+
830+ class Band
831+ include Mongoid::Document
832+ field :_id, type: String
833+ end
834+
835+ If the default on ``_id`` is omitted, and no ``_id`` value is provided by
836+ your application, Mongoid will persist the document without the ``_id``
837+ value and one will be assigned by the server. However, Mongoid will
838+ not automatically retrieve this value when the document is persisted - you
839+ must obtain the persisted value (and the complete persisted document) using
840+ other means:
841+
842+ .. code-block:: ruby
843+
844+ band = Band.create!
845+ => #<Band _id: , >
846+ band.id
847+ => nil
848+ band.reload
849+ # raises Mongoid::Errors::DocumentNotFound
850+ Band.last
851+ => #<Band _id: 5fc681c22c97a6791f324b99, >
852+
853+ Omitting ``_id`` fields is more common in :ref:`embedded documents <omit-id>`.
854+
855+ Mongoid also defines the ``id`` field aliased to ``_id``. The ``id``
856+ alias can :ref:`be removed <unalias-id>` if desired (such as to integrate
857+ with systems that use the ``id`` field to store value different from ``_id``.
858+
820859
821860.. _bson-symbol:
822861
0 commit comments