Javascript 从Firestore读取不会返回任何结果
我正在尝试从函数到Firestore的读/写操作,但在读、写操作方面存在问题。我提供了以下示例,但下面的查询(及其变体)返回空承诺:Javascript 从Firestore读取不会返回任何结果,javascript,node.js,firebase,google-cloud-firestore,google-cloud-functions,Javascript,Node.js,Firebase,Google Cloud Firestore,Google Cloud Functions,我正在尝试从函数到Firestore的读/写操作,但在读、写操作方面存在问题。我提供了以下示例,但下面的查询(及其变体)返回空承诺: module.exports.customerByPhone = phone => { return db.collection('customers') .limit(1) .get(); // .where('phoneNumber', '==', phone).get(); }; 正如你所看到的,最初我尝试着去哪里——
module.exports.customerByPhone = phone => {
return db.collection('customers')
.limit(1)
.get();
// .where('phoneNumber', '==', phone).get();
};
正如你所看到的,最初我尝试着去哪里——空洞的承诺,我也尝试着去做——同样的结果
以下是我如何插入数据:
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}`));
}
现在查询部分突出返回一个元素impl:
module.exports.customerByPhone = phone => {
return db.collection('customers')
// .where('phoneNumber', '==', phone)
.limit(1)
.get()
};
最后一张来自db的图片,不是EN而是水晶般干净:
我错过了什么???您正在将电话号码存储为整数:
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知道您要存储字符串。然后,使用相同字符串的查询将找到该文档