【问题标题】:Is there any way I can query Firestore query condition based on fields有什么方法可以根据字段查询 Firestore 查询条件
【发布时间】:2021-04-09 13:29:47
【问题描述】:

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

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

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

【问题讨论】:

  • 你好。你能为这行提供一个例子吗?:“我想显示用户只能看到未被阻止的用户的列表。”我觉得很难理解。阻止用户列表是否包含数字?还是用户子集合的数组?。
  • 该应用程序就像我们在 facebook 中拥有的社交媒体一样,用户可以阻止任何其他用户,所以在主页上我向用户显示朋友卡,并且当用户阻止他的任何朋友时有阻止朋友选项那么该朋友将不会出现在这些列表中
  • 您添加的代码似乎正如您所提到的,获取了所有用户,但您尝试过滤它们?

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


【解决方案1】:

我了解到您的 Firestore 收藏与此类似:

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

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 和另一个stackoverflow question 中引用的方法firebase.firestore.FieldPath.documentId(),因为id 不能像where 子句中的其他文档字段一样传递。

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

我希望你觉得这很有用。

【讨论】:

    猜你喜欢
    • 2019-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-23
    • 1970-01-01
    相关资源
    最近更新 更多