ruby-on-railsrubymongoidmongoid4

How to retrieve a mongoid document _id after it was persisted?


Sorry if it's trivial, but I can't find an answer, so maybe I don't know how to ask the question. I have a simple case:

I do:

SomeMongoidObject.new.save

And after that I want to use the id of new object to start a new background worker process. I can't find how can I get the _id of the newly created object? The save method returns a status.

Could you help me with that?


Solution

  • Did you try this?

    mongoid_object = SomeMongoidObject.new
    mongoid_object.save
    

    Now you can get the id by simply doing one of the following

    mongoid_object.id #=> id will be returned
    

    or

    mongoid_object["_id"]
    

    or

    mongoid_object._id
    

    Hope this helps!