Can I use String as ID type for mongodb document?

前端 未结 5 2055
死守一世寂寞
死守一世寂寞 2021-02-18 17:11

I am using java/morphia to deal with mongodb. The default ObjectId is not very convenient to use from Java layer. I would like to make it a String type while keep the key genera

5条回答
  •  梦毁少年i
    2021-02-18 17:35

    I would like to add that it is not always a good idea to use the automatically generated BSON ObjectID as a unique identifier, if it gets passed to the application: it can potentially be manipulated by the user.

    ObjectIDs appear to be generated sequentially, so if you fail to implement the necessary authorization mechanisms, malicious user could simply increment the value he has, to access resources he should not have access to.

    UPDATE: Since version 3.4+ the ObjectIDs are no longer generated incrementally. Please see 3.2 docs vs the latest docs

    Therefore using UUID type identifiers will provide a layer of security-through-obscurity. Of course, Authorization (is this user allowed to access requested resource) is a must, but you should be aware of the aforementioned ObjectID feature.

    To get the best of both worlds, generate UUID which matches your ObjectID length (12 or 24 characters) and use it to create your own _id of ObjectID type.

提交回复
热议问题