我正在尝试从函数读取/写入 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()
};
我错过了什么?
最佳答案
您将电话号码存储为整数:
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/