简体   繁体   English

Firebase array-contains - 搜索值而不是键

[英]Firebase array-contains - search through the values not the keys

How do you query for a value in an array that has a numeric keyset?如何查询具有数字键集的数组中的值?

For example this query does not work because I believe it is looking at the indexing rather then the values:例如,此查询不起作用,因为我相信它正在查看索引而不是值:

var db = firebase.firestore();
var users = db.collection("Users");
var currentUser = firebase.auth().currentUser;
var result = users.where('liked', 'array-contains', currentUser.uid);
if (result.length > 0) {
  return 'You have a match!';
} else {
  return 'No matches';
}

在此处输入图像描述

As Stratubas commented, the problem is in this code:正如 Stratubas 评论的那样,问题出在这段代码中:

var result = users.where('liked', 'array-contains', currentUser.uid);

This code constructs a query, but does not yet execute the query.此代码构造查询,但尚未执行查询。 So result is a Query object .所以result是一个Query对象 To execute the query, and get the results from the server, you call get() on the query , which then returns a Promise<QuerySnapshot> .要执行查询并从服务器获取结果,您可以在查询上调用get() ,然后返回一个Promise<QuerySnapshot> Once the promise results, you can handle the results in the QuerySnapshot object .一旦承诺结果,您可以在QuerySnapshot对象中处理结果。

var query = users.where('liked', 'array-contains', currentUser.uid);
query.get().then(function(querySnapshot) {
  if (querySnapshot.size > 0) {
    console.log('You have a match!');
  } else {
    console.log('No matches');
  }
});

In more modern JavaScript, the above can also be written as:在更现代的 JavaScript 中,上面的内容也可以写成:

let query = users.where('liked', 'array-contains', currentUser.uid);
let querySnapshot = await query.get()
if (querySnapshot.size > 0) {
  console.log('You have a match!');
} else {
  console.log('No matches');
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Firebase Firestore - 复合查询中包含多个数组 - Firebase Firestore - Multiple array-contains in a compound query Firebase 使用数组包含和范围过滤器进行查询 JavaScript - Firebase Query using array-contains and a range filter JavaScript Firestore:多个“数组包含” - Firestore: Multiple 'array-contains' 在 firestore 中查询数据并遍历数组时,有没有办法使用 where() function 和“array-contains” - Is there a way to use the where() function and "array-contains" when querying data in firestore and iterate through an array 具有高级公共/令牌规则和数组包含的 Firestore 安全规则 - Firestore Security Rules with advanced public/token rules and array-contains 如何在firestore web接口中使用array-contains - How to use array-contains in firestore web interface 无法在云中使用“数组包含”where 子句 function - Unable to use 'array-contains' where clause in cloud function 为什么 Firestore 中数组包含的每个项目都有两个索引条目? - Why are there two index-entries for each item for array-contains in Firestore? 在firebase实时数据库中用数组搜索 - Search with array in firebase realtime database 在 firebase 数组中如何按一个元素的值进行搜索? - In a firebase array how to search by value of one element?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM