简体   繁体   English

Mongodb / Morphia和RESTful API-如何处理ID?

[英]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. Mongodb建议为每个持久化文档都使用一个ObjectId ID,但是对于RESTful API而言,效果并不好,因为RESTful API中的URL通常包含简短的,易于记忆的ID,例如/users/12/about/projects/1/users等。

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? _id为长整数并使用counters集合来跟踪它们?
  • leaving _id alone and creating a separate field for those sequential numbers? 留下_id并为这些序号创建一个单独的字段?
  • something else? 还有什么吗

Thanks!! 谢谢!!

I wouldn't change the _id if you want to use it for @Reference . 如果您要将_id用于@Reference则不会更改。 (At least historically) this has led to issues with references. (至少在历史上)这导致了引用的问题。

A separate id field is probably a better solution. 单独的id字段可能是一个更好的解决方案。 Or (if available) use a natural ID. 或者(如果可用)使用自然ID。 For example if there's a unique username, use that instead of a numeric ID. 例如,如果有唯一的用户名,请使用该用户名代替数字ID。

You can use whatever you'd like for your IDs. 您可以使用任何您想要的ID。 If you don't let mongodb assign an ObjectId on insertion, you'd just have to manage those IDs and guarantee their uniqueness yourself. 如果您不让mongodb在插入时分配ObjectId,则只需要管理这些ID并自己保证其唯一性即可。 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. 但是,如果这是您的需要,那么这样做绝对没有错。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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