android firestore adds up date on top of duplicate data

Viewed 64

firestore dataset

As you can see in the image, whenever I try to update(not replace) a field with a new value, it duplicates the data, and adds up on top of the duplicate. What is causing this issue?

Whenever a user posts, I need to add the post id to an existing array of post ids.

hierarchy:

users - collection - document(emblem(String), photo(String), postIds(String[])...)

mDb = FirebaseFirestore.getInstance();

        // remove old ids
        Map<String, Object> oldIds = new HashMap<>();
        oldIds.put("posts", _oldPostList);

        // add new ids
        Map<String, Object> newIds = new HashMap<>();
        _oldPostList.add(_newValue);
        newIds.put("posts", _oldPostList);

        String docId = FirebaseAuth.getInstance().getCurrentUser().getEmail();

        DocumentReference docRef = mDb.collection("users").document(docId);

        docRef.update("posts", FieldValue.arrayRemove(oldIds)).addOnSuccessListener(new OnSuccessListener<Void>() {
            @Override
            public void onSuccess(Void unused) {
                docRef.update("posts", FieldValue.arrayUnion(newIds)).addOnSuccessListener(new OnSuccessListener<Void>() {
                    @Override
                    public void onSuccess(Void unused) {
                        sendBroadcast(_context, _action, true, null);
                    }
                }).addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        sendBroadcast(_context, _action, false, null);
                    }
                });
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                sendBroadcast(_context, _action, false, null);
            }
        });
1 Answers

I assume the structure you want is a list of posts, not a list of maps of lists of posts. If that is the case, the problem is that you are supplying the "posts" key twice - once in the update call and again in the data (Map) you pass. Instead of putting the post list into a map and passing the map like this

// Don't do this - creates a list of maps, not a list of posts
Map<String, Object> oldIds = new HashMap<>();
oldIds.put("posts", _oldPostList);
docRef.update("posts", FieldValue.arrayRemove(oldIds));

you should just pass the list directly, since the update call already defines the "posts" key.

If you just want to add a new post to the list, you don't need to remove the old list first either. You can just use arrayUnion to add the new post to the existing list like this:

docRef.update("posts", FieldValue.arrayUnion(_newValue));

Take a look at the Firestore docs for some more examples too.

Related