Search code examples
mongodbrestmorphia

Mongodb / morphia and a RESTful APIs - how to handle ids?


Mongodb recommends having an ObjectId id for every persisted document, but that doesn't go very well with RESTful APIs where urls often include short, easy to remember ids like /users/12/about or /projects/1/users and so forth.

What are the best practices to dealing with this?

  • having _id be a long number and use a counters collection to keep track of them?
  • leaving _id alone and creating a separate field for those sequential numbers?
  • something else?

Thanks!!


Solution

  • I wouldn't change the _id if you want to use it for @Reference. (At least historically) this has led to issues with references.

    A separate id field is probably a better solution. Or (if available) use a natural ID. For example if there's a unique username, use that instead of a numeric ID.