我有以下数据结构,想返回与标签关联的“产品”。是否有可能用当前的数据结构实现这一目标?如果不是,我应该如何构造数据,以及返回所有具有“标签 2”的“产品”的查询是什么样的?
{
"accounts" : {
"-KRPU3FyKT4oPWHYjDrr" : {
"userId" : "1"
},
"-kjnsvakljsndfme;lnmv" : {
"userId" : "2"
}
},
"products" : {
"-KXcnfob3Vo3s8bL9WSI" : {
"name" : "Product 1",
"description" : "Description of product 1",
"tags" : [ "Tag 1", "Tag 2", "Tag 3", "etc." ],
"url" : "websiteURL1.com",
},
"-KXcnfob3Vo3s8bL9WSI" : {
"name" : "Product 2",
"description" : "Description of product 2",
"tags" : [ "Tag 1", "Tag 2", "Tag 3", "etc." ],
"url" : "websiteURL2.com",
}
}
}
我最后一次尝试是这样的:
firebase.database().ref.child('products').orderByChild('tags').equalTo("Tag 1").once('value', function(products)
显然没有成功.. 然而,这确实会返回所有带有标签的“产品”:
firebase.database().ref.child('products').orderByChild('tags').once('value', function(products)
提前致谢!
最佳答案
如果您像这样重组数据:
"products" : {
"-KXcnfob3Vo3s8bL9WSI" : {
"name" : "Product 1",
"description" : "Description of product 1",
"tags" : {
"Tag1": true,
"Tag2": true
},
"url" : "websiteURL1.com"
},
"-KXcnfob3Vo3s8bL9WSI" : {
"name" : "Product 2",
"description" : "Description of product 2",
"tags" : {
"Tag3": true,
"Tag4": true
},
"url" : "websiteURL2.com"
}
}
您可以使用深度路径查询来获取具有特定标签的产品:
firebase.database()
.ref('products')
.orderByChild('tags/Tag1')
.equalTo(true)
.once('value', function (products) {
console.log(products.val());
});
请注意,只有当您拥有固定数量的已知标签时,此方法才有效,因为每个标签都需要一个索引。
关于javascript - 非规范化 Firebase 数据以进行标签搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40952401/