为了账号安全,请及时绑定邮箱和手机立即绑定

Firestore“where”查询未按预期工作

Firestore“where”查询未按预期工作

慕雪6442864 2023-06-09 10:40:36
我正在尝试从我的 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    }  }}我正在通过邮递员对此进行测试。我已经尝试将 firebase 规则更改为适用于任何事物,但似乎仍然没有任何效果。更新:以下是我初始化数据库的方式const admin = require('firebase-admin');admin.initializeApp();const db = admin.firestore();module.exports = { admin, db };
查看完整描述

2 回答

?
达令说

TA贡献1821条经验 获得超6个赞

您的代码需要一个文档,但必须为查询返回多个文档做好准备。当您在 Query 对象上运行时get(),它将产生一个QuerySnapshot对象。正如您从 API 文档中看到的那样,它没有属性exists。该属性的检查将始终为“假”。您要做的是检查结果,首先查看是否有任何文档,然后获取第一个:

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

            }

        })


查看完整回答
反对 回复 2023-06-09
?
HUWWW

TA贡献1874条经验 获得超12个赞

现在你需要使用

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


查看完整回答
反对 回复 2023-06-09
  • 2 回答
  • 0 关注
  • 92 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信