简体   繁体   中英

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!!

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.

You can use whatever you'd like for your IDs. If you don't let mongodb assign an ObjectId on insertion, you'd just have to manage those IDs and guarantee their uniqueness yourself. This is not a problem but it can take a bit of work to make sure it's right. But if that's what you need, there's absolutely nothing wrong with doing so.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM