javascript - 从 Firestore 读取不会返回任何内容

标签 javascript node.js firebase google-cloud-firestore google-cloud-functions

我正在尝试从函数读取/写入 Firestore,但读取时遇到问题,写入工作正常。我正在遵循 here 提供的示例,但下面的查询(及其变体)返回空的 promise :

module.exports.customerByPhone = phone => {
    return db.collection('customers')
    .limit(1)
    .get();
    // .where('phoneNumber', '==', phone).get();
};

正如你所见,最初我尝试使用 where - 空洞的 promise ,我也尝试使用 whatever - 相同的结果。

这是我插入数据的方法:

db.collection('customers').add({
        phoneNumber: 123456,
        active: true,
        registration: new Date()
    }).then(it => console.log(`added ${it}`));

Package.json 片段:

"dependencies": {
    "firebase-admin": "^8.6.0",
    "firebase-functions": "^3.3.0"
  }

还有一些身份验证逻辑:

const key = require("../firebase.key.json");
//
admin.initializeApp({
    credential: admin.credential.cert(key),
    databaseURL: "https://cant-touch-this.firebaseio.com"
});
const db = admin.firestore();

编辑

这是更完整的应用程序流程,

请求处理程序如下所示:

module.exports.handle = (req, res) => {
    // doInsert and query below are just for test purposes
    db.doInsert();
    db.customerByPhone(req.body.phoneNumber).then(function (doc) {
        if (doc.exists) {
            console.log("Document data:", doc.data());
        } else {
            // doc.data() will be undefined in this case
            console.log("No such document!");
        }
    });
    ...
}

正如我所说,doInsert 有效,实现:

module.exports.doInsert = () => {
    db.collection('customers').add({
        phoneNumber: 123456,
        active: true,
        registration: new Date()
    }).then(it => console.log(`added ${it}`));
}

现在是查询部分,它只是返回一个元素,即:

module.exports.customerByPhone = phone => {
    return db.collection('customers')
        // .where('phoneNumber', '==', phone)
        .limit(1)
        .get()
};

最后一张来自数据库的图片,不是英语,但非常干净: enter image description here

我错过了什么?

最佳答案

您将电话号码存储为整数:

db.collection('customers').add({
    phoneNumber: 123456,  // THIS IS AN INTEGER
    active: true,
    registration: new Date()
})

但是您正在使用字符串查询它:

// req.body.phoneNumber is a string
db.customerByPhone(req.body.phoneNumber)

在 Firestore 中,字符串和数字永远不会彼此相等,因此此查询永远不会起作用。

因为电话号码并不是真正的整数。它们不代表数值,并且您永远不会与它们匹配。因此,您应该将它们存储为字符串:

db.collection('customers').add({
    phoneNumber: '123456',  // THIS IS A STRING
    active: true,
    registration: new Date()
})

在调用 add() 时在数字两边加上引号,以便 Firebase 知道您要存储字符串。然后使用相同字符串的查询将找到该文档。

关于javascript - 从 Firestore 读取不会返回任何内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59499596/

相关文章:

javascript - 多步骤表单按钮禁用,直到表单选择字段

node.js - 控制台输入不正确?

javascript - 如何使用aes-128-cbc算法实现CryptoJS解密?

swift - 我不想要求我的应用程序登录,但如何将它们的数据分开?

Firebase 托管的字体总是返回 404

javascript - 使用 jQuery 反转 CSS 动画

javascript - 如何使用 jQuery 隐藏 div

javascript - Jquery:将 SVG 转换为新尺寸的 PNG

Node.js 快速连接被/拒绝

ios - AuthDataResult 类型的值没有成员 providerID