Add new field or change the structure on all Firestore documents

前端 未结 5 700
感动是毒
感动是毒 2021-02-02 13:11

Consider a collection of users. Each document in the collection has name and email as fields.

{
  \"users\": {
    \"uid1\         


        
5条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-02 13:19

    I am guessing that last_login is a primitive data type, maybe a long to hold a timestamp. An auto-generated setter would look like this:

    private long last_login;
    
    public void setLast_login(long last_login) {
        this.last_login = last_login;
    }
    

    This leads to a crash when old documents that lack the field are fetched due to null assignment to a variable of a primitive data type. One way around it is to modify your setter to pass in a variable of the equivalent wrapper class - Long instead of long in this case, and put a null check in the setter.

    private long last_login;
    
    public void setLast_login(Long last_login) {
        if(last_login != null) {
            this.last_login = last_login;
        }
    }
    

    The cost of avoiding the null pointer exception is the boxing-unboxing overhead.

提交回复
热议问题