gpt4 book ai didi

javascript - Firestore 难题!对数组和字符串使用 .where()

转载 作者:行者123 更新时间:2023-11-30 14:00:20 31 4
gpt4 key购买 nike

我正在尝试使用 firestore 的 .where() 功能来检测某个字符串是否在数据库的数组中。我曾尝试通过添加方括号和其他东西来表示数组的一部分来操纵函数的第一个参数,但无济于事。

//in this section I am getting the "yourLikes" integer (unrelated to the problem)
var liks = [];
var tempLiks = []
db.collection("users").where("uid", "==", uid)
.get()
.then(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
tempLiks = doc.data().yourLikes;
// I am using a setTimeout() function to allow firebase to
// process the previous query and give me the doc.data().yourLikes for tempLiks
setTimeout(function(){
//Right here, the "usersLiked" data is an array, with a bunch of different values.
// I am trying to see if one of those values is doc.data().uid from my previous query. (I think) this is the problem.
db.collection("memeInfo").where("usersLiked", "==", doc.data().uid)
.get()
.then(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
for (var i = 0; i < tempLiks.length; i++) {
liks.push([tempLiks[i],doc.data().likes])
console.log(liks)
}
})
})
},500)

如果有人有解决方案来查询各个值是否在数组中,而无需永远使用 for 循环(我可能在 usersLiked 数组中有数千个值),将不胜感激。

最佳答案

您应该使用 array_contains 运算符根据数组值进行过滤,请参阅 https://firebase.google.com/docs/firestore/query-data/queries#array_membership .

因此您必须按如下方式调整您的代码:

//....
db.collection("memeInfo").where("usersLiked", "array-contains", doc.data().uid)
.get()
.then(function(querySnapshot) {...})

补充说明:使用 setTimeout() 来管理对 Firestore 的异步查询并不是正确的方法(不保证查询会完成不到 500 毫秒)。您应该通过 get() 方法返回的 promise 来管理异步性。特别是,由于您并行触发多个查询(通过循环),因此您需要使用 Promise.all() .


更新 在您发表评论后。您可以按如下方式使用 Promise.all():

var liks = [];
var tempLiks = [];
db.collection('users')
.where('uid', '==', uid)
.get()
.then(function(querySnapshot) {
// Here the Promise returned by the get() method is fulfilled, so you do have the results of the query and you do'nt need to use setTimeout

var queries = [];
querySnapshot.forEach(function(doc) {
tempLiks = doc.data().yourLikes;

//We push each query to the queries array

queries.push(
db
.collection('memeInfo')
.where('usersLiked', '==', doc.data().uid)
.get()
);
});

//Then we call Promise.all()

return Promise.all(queries);
})
.then(function(results) {
//As explained in the doc "The returned promise is fulfilled with an array containing all the values of the iterable passed as argument (the queries array)."
//So result is an array of QuerySnapshots, since the get() method returns a QuerySnapshot
//Do whatever you want with the array
console.log(results);
results.forEach(function (querySnapshot) {
querySnapshot.forEach(function (doc) {
//.....
});
});
});

关于javascript - Firestore 难题!对数组和字符串使用 .where(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56421817/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com