如何在 Firebase Firestore 中执行简单搜索以检查集合中是否存在记录?我在文档中看到过这段代码,但它并不完整。
// Create a reference to the cities collection
var citiesRef = db.collection('cities');
// Create a query against the collection
var queryRef = citiesRef.where('state', '==', 'CA');
在我的用例中,我想检查给定号码的拒绝联系人集合。这是我的代码
const collectionRef = db.collection('rejectedContacts');
const queryRef = collectionRef.where('contact','==',phone);
let contactRejected: boolean = queryRef.get.length>0 ;
if (contactRejected) {
return response.json(
{
status: 0,
message: `Contact , ${phone} is blocked. Please try again with another one.`,
result: null
});
}
我已经使用被拒绝的号码检查了该函数,该号码是我在集合中手动添加的,但它没有响应被拒绝的消息。如何使用选择查询获取计数或行本身。我的代码有什么问题吗?
UPDATE 1正如 @Matt R 所建议的,我用这个更新了代码
let docRef = db.collection('rejectedContacts').where('contact', '==', phone).get();
docRef.then(doc => {
if (!doc.empty) {
return response.json(
{
status: 0,
message: `Contact , ${phone} is blocked. Please try again with another one.`,
result: null
});
} else {
return response.json(
{
status: 0,
message: `Contact , ${phone} is not blocked`,
result: null
});
}
})
.catch(err => {
console.log('Error getting document', err);
});
但是当检查现有号码时,它正在返回并且没有被阻止
Edit 2
return collectionRef.select('contact').where('contact', '==', phone).get()
.then(snapShot => {
let x : string = '['
snapShot.forEach(doc => {
console.log(doc.id, '=>', doc.data());
x+= `{${doc.data}},`;
});
return response.send(x);
});
它仅从该行返回 x 的值
let x : string = '['