簡體   English   中英

Firestore“where”查詢未按預期工作

[英]Firestore "where" query not working as expected

我正在嘗試從我的 firestore 數據庫中進行一個簡單的查詢,但我遺漏了一些非常明顯的東西。 我嘗試在網上查找,但沒有任何效果。 對於某些背景,我有一個“cf”集合,我試圖在其中查詢“hsc”值等於“1”但我沒有得到任何回報的對象。

在此處輸入圖像描述

exports.getOneTodo = (request, response) => {
    db
        .collection('cf')
        .where("hsc", "==", "1") 
        .get()
        .then((doc) => {

            if (!doc.exists) {
                return response.status(404).json(
                    { 
                        error: 'Todo not found' 
                    });
            }
            TodoData = doc.data();
            TodoData.todoId = doc.id;
            return response.json(TodoData);
        })
        .catch((err) => {
            console.error(err);
            return response.status(500).json({ error: error.code });
        });
};

在此處輸入圖像描述 以下是firestore規則。

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write
    }
  }
}

我正在通過 postman 進行測試。 我嘗試將 firebase 規則更改為適用於任何事情,但似乎沒有任何效果。

更新:以下是我初始化數據庫的方式

const admin = require('firebase-admin');

admin.initializeApp();

const db = admin.firestore();

module.exports = { admin, db };

您的代碼需要一個文檔,但它必須為查詢返回多個文檔做好准備。 當您在 Query 對象上運行get()時,它將產生一個QuerySnapshot對象。 正如您從 API 文檔中看到的,它沒有exists屬性。 對該屬性的檢查將始終為“false”。 你必須做的是檢查結果,首先看看是否有任何文件,然后獲取第一個:

    db
        .collection('cf')
        .where("hsc", "==", "1") 
        .get()
        .then((qsnapshot) => {
            if (qsnapshot.docs.length > 0) {
                const dsnapshot = qsnapshot.docs[0];
                // send the response using dsnapshot.data()
            }
            else {
                // send the response saying nothing was found
            }
        })

現在你需要使用

  db.collection("id").whereGreaterThan("field","value")
  .whereEqualTo("field","value")
  .whereLessThen("field","value")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM