0

As a relational database provides an auto-increment to the id for entity. I wonder could we do the same or create another UID specifically for that entity. For example, I have a User entity, which using Mongo driver POJO and wants to have the userId auto-increment it, but ones advised that is not safe to do as would break the Object ID. So, if I want to use it, how can I use and show each userId with 1...N?

    public class User {
    
        private ObjectId id;
    
        @BsonProperty(value = "userId")
        private Long userId;
        private String email;
        private String fullName;
        // private String lastName;
        private String password;
    
    // getter & setter
}
Stu_Dent
  • 370
  • 1
  • 4
  • 19
  • 2
    The `ObjectId` _is_ the MongoDB analog to an auto-increment field. (Note that it's not great to use auto-increment for a user ID anyway, since it leaks information and is predictable.) In general, I usually see the `_id` field treated as a `String` in Java and then handled as any opaque identifier. – chrylis -cautiouslyoptimistic- Oct 10 '20 at 03:41
  • @chrylis-cautiouslyoptimistic- I came across the `_id` of Mongodb that people use String type too. This is where I having trouble to use this object id to be Primary key to work with CRUD e.g. get id for the user using the `_id` and return a `null` value. – Stu_Dent Oct 11 '20 at 03:05

0 Answers0