[英]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.