Can I use String as ID type for mongodb document?

前端 未结 5 2028
死守一世寂寞
死守一世寂寞 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条回答
  •  爱一瞬间的悲伤
    2021-02-18 17:17

    I actually did the same thing because I was having some problem converting the ObjectId to JSON.

    I then did something like

    @Id
    private String id;
    public String getId() {
        return id();
    }
    public void setId(String id) {
        this.id = id;
    }
    

    And everything worked fine untill I decided to update a previously inserted document, when i got the object by Id sent it to the page via JSON and receive the same updated object also by JSON post and then used the save function from the Datastore, instead of updating the previous data it inserted a new document instead of updating the one that was already.

    Even worst the new document had the same ID than the previously inserted one, something i thought was impossible.

    Anyway i setted the private object as an ObjectID and just left the get set as string and then it worked as expected, not sure that helps in your case thought.

    @Id
    private ObjectId id;
    public String getId() {
        return id.toString();
    }
    public void setId(String id) {
        this.id = new ObjectId(id);
    }
    

提交回复
热议问题