Firebase array-contains - 搜索值而不是键
Firebase array-contains - search through the values not the keys
如何查询具有数字键集的数组中的值?
例如,这个查询不起作用,因为我相信它正在查看索引而不是值:
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';
}
正如 Stratubas 评论的那样,问题出在这段代码中:
var result = users.where('liked', 'array-contains', currentUser.uid);
此代码构造查询,但尚未执行查询。所以 result
是 Query
object. To execute the query, and get the results from the server, you call get()
on the query, which then returns a Promise<QuerySnapshot>
. Once the promise results, you can handle the results in the QuerySnapshot
object.
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');
}
});
更现代的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');
}
如何查询具有数字键集的数组中的值?
例如,这个查询不起作用,因为我相信它正在查看索引而不是值:
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';
}
正如 Stratubas 评论的那样,问题出在这段代码中:
var result = users.where('liked', 'array-contains', currentUser.uid);
此代码构造查询,但尚未执行查询。所以 result
是 Query
object. To execute the query, and get the results from the server, you call get()
on the query, which then returns a Promise<QuerySnapshot>
. Once the promise results, you can handle the results in the QuerySnapshot
object.
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');
}
});
更现代的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');
}