有什么方法可以根据字段查询 Firestore 查询条件

时间:2021-01-03 14:46:43

标签: javascript firebase react-native google-cloud-firestore

我在 React Native 应用中使用 Firebase。我有一个用户集合,我有文档,文档的 ID 是自定义的(使用用户的电话号码作为 ID),并且我已经阻止了用户数组字段,我将在其中添加被阻止的用户由用户。我想显示用户只能看到未被阻止的用户的列表。

我正在获取所有用户列表,我想过滤它们并只获取未被用户阻止的人。

var getUsersList = async() => {
  const findUser = await firestore().collection('users').get();
  if (findUser.docs[0] != undefined && findUser.docs[0]._exists){
    setUserList(findUser.docs)
  }
}

1 个答案:

答案 0 :(得分:0)

我了解到您的 firestore 集合与此类似:

enter image description here

如果是这样,那么我已经在以下三个功能中构建了您的需求:

1.readBlockedNumbers 返回用户拥有的屏蔽号码数组。
2.show_nonBlockedUsers从前面的方法接收被屏蔽号码的数组,并显示不在这个数组中的用户。
3. test 来协调以上两种方法的执行。

const admin = require('firebase-admin');
const serviceAccount = require('/home/keys.json');

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount)
});

const db = admin.firestore();

async function readBlockedNumbers(docId){
  const userRef = db.collection('users').doc(docId);
  const doc = await userRef.get();
  if (!doc.exists) {
    console.log('No such document!');
    return [];
  } 
  else 
  {
    return doc.data()['blocked_numbers'];
  }

async function show_nonBlockedUsers(blocked_users){
  console.log('Array length:', blocked_users.length);
  
  if(blocked_users.length == 0)
  return;
  
  const userRef = db.collection('users');
  const snapshot = await userRef
    .where(admin.firestore.FieldPath.documentId(), 'not-in', blocked_users)
    .get();
  
  if (snapshot.empty) {
    console.log('No matching documents.');
    return;
  }  
  
  snapshot.forEach(doc => {
    console.log(doc.id, '=>', doc.data());
  });
}

async function test(){
  const docId = '202-555-0146';
  //'202-555-0102'
  const blocked_users = await readBlockedNumbers(docId);
  await show_nonBlockedUsers(blocked_users);
}

这里重要的是如何使用 not-in 运算符和方法 admin.firestore.FieldPath.documentId().
我发现 not-in 运算符 here 和方法 firebase.firestore.FieldPath.documentId() 在这个其他 stackoverflow question 中引用,因为 id 不能像 where 中的其他文档字段一样传递子句。

请参阅 firebase documentation 以及 not-in 运算符的限制。

我希望你觉得这很有用。