Firestore检查集合中是否存在文档

时间:2019-06-28 15:53:04

标签: android google-cloud-firestore

我正在尝试编写用于将商品/库存上传到Firestore的代码。我想要的是如果该物品已经在Firestore中注册,然后重新计算数量。但是,如果该项目尚未在Firestore中注册,则系统会将新文档添加到Firestore中。

我已经制作了如下代码,如果我尝试添加已经注册的项目,它会成功重新计算数量,但是问题是当我想添加新项目(未在数据库中注册)时,它不起作用。有人可以修复我的代码。

final FirebaseFirestore db = FirebaseFirestore.getInstance();

        merk = etMerk.getText().toString().trim();
        type = etType.getText().toString().trim();
        typemerk = type + " - " + merk;
        qty = etQty.getText().toString().trim();
        price = etPrice.getText().toString().trim();
        date = datetime.getText().toString();

        final Map<String, Object> stock = new HashMap<>();
        stock.put("date", date);
        stock.put("type", typemerk);
        stock.put("qty", qty);
        stock.put("price", price);
        stock.put("merk", merk);


        final FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
        final CollectionReference documentReference = rootRef.collection("watchlist");
        Query query = documentReference.whereEqualTo("type", typemerk);
        query.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
            @Override
            public void onComplete(@NonNull Task<QuerySnapshot> task) {
                if (task.isSuccessful()) {
                    for (QueryDocumentSnapshot document : task.getResult()) {
                        Log.d(Tag.ITEM, document.getId() + "=>" + document.getData());

                        String id = document.getString("id");
                        String oldqty = document.getString("qty");
                        Integer i = Integer.parseInt(oldqty) + Integer.parseInt(qty);
                        String newQty = String.valueOf(i);

                        Map<Object, String> map = new HashMap<>();
                        map.put("qty", newQty);
                        rootRef.collection("watchlist").document(document.getId()).set(map, SetOptions.merge());
                        Toast.makeText(AddItemActivity.this, "Berhasil menambah stok", Toast.LENGTH_SHORT).show();
                        progressBar.setVisibility(View.GONE);
                    }
                } else {
                    Log.d(Tag.ITEM, "not register in DB", task.getException());
                    Toast.makeText(AddItemActivity.this, "new item to database", Toast.LENGTH_SHORT).show();
                    documentReference
                            .add(stock)
                            .addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
                                @Override
                                public void onSuccess(DocumentReference documentReference) {
                                    Toast.makeText(AddItemActivity.this, "Berhasil Memasukkan Barang ke Stok", Toast.LENGTH_SHORT).show();
                                    progressBar.setVisibility(View.GONE);
                                    etMerk.setText("");
                                    etType.setText("");
                                    etQty.setText("");
                                    etPrice.setText("");
                                    etMerk.setFocusable(true);
                                }
                            })
                            .addOnFailureListener(new OnFailureListener() {
                                @Override
                                public void onFailure(@NonNull Exception e) {
                                    Toast.makeText(AddItemActivity.this, "Gagal Memasukkan stok, silahkan coba lagi.", Toast.LENGTH_SHORT).show();
                                    progressBar.setVisibility(View.GONE);
                                }
                            });
                }
            }
        });
    }

1 个答案:

答案 0 :(得分:0)

您应该检查以确保查询成功返回并且不为空。如果查询已处理但没有匹配的结果,它将返回空结果。

 FirebaseFirestore db = FirebaseFirestore.getInstance();

    db.collection("myCollection")
            .whereEqualTo("myQuery", myQueryValue)
            .get()
            .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                @Override
                public void onComplete(@NonNull Task<QuerySnapshot> task) {

                    boolean documentExists;

                    if(task.isSuccessful()){
                        Log.d("QueryResult", "Is query result empty: " + task.getResult().isEmpty());
                        documentExists = !task.getResult().isEmpty();

                    }else{
                        Log.e("QueryResult", "Error getting documents.", task.getException());
                        documentExists = false;
                    }

                    if(documentExists){
                        Log.d("QueryResult", "The document exists");
                        // Do whatever you need to do with the document
                    }else{
                        Log.d("QueryResult", "The document doesn't exist or there was an error retrieving it");
                        // Create the document or whatever else you need to do
                    }
                }
            });