在 Firebase Firestore 中执行简单的选择查询

2024-01-13

如何在 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 = '['

Firestore 的 get() 方法返回一个承诺和响应,我会尝试以这种格式来处理文档是否存在。在故障排除时,此格式还可以提供更好的错误消息。

编辑/更新:使用 where 子句返回必须迭代的快照,因为它can返回多个文档。请参阅此处的文档:https://firebase.google.com/docs/firestore/query-data/get-data#g​​et_multiple_documents_from_a_collection https://firebase.google.com/docs/firestore/query-data/get-data#get_multiple_documents_from_a_collection

使用您的示例更新了代码。

var collectionRef = db.collection('rejectedContacts');
var query = collectionRef.where('contact','==',phone).get()
.then(snapshot => {
    snapshot.forEach(doc => {
        console.log(doc.id, '=>', doc.data());
    });
})
.catch(err => {
    console.log('Error getting documents', err);
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 Firebase Firestore 中执行简单的选择查询 的相关文章