【发布时间】:2022-01-06 21:22:54
【问题描述】:
可以按字母顺序对数据库列表进行排序吗? 我尝试了 sortby() 函数,但它不能正常工作
var snapshot = await firebase.firestore().collection('Locations').where(
"category", "==", type).orderBy('name','desc').get();
例如在数据库中: 1-名称:鸡 2-名称:猪 3- 名字:鸭子
按名称排序后,顺序应该是 鸡鸭猪
这是我的完整代码:
export default function filtercat(type,sortformat){
var locList = []
const filterbytype = async() =>{
if (sortformat == 'rating'){
// will filter by the type of location, and then sort by rating
var snapshot = await firebase.firestore().collection('Locations').where(
"category", "==", type).orderBy('rating','desc').get();
// this is for All category, it will display all locations
if (type == 'All'){
var snapshot = await firebase.firestore().collection('Locations').orderBy('rating','desc').get()
}
if (snapshot.empty){
console.log('No matching documents');
return;
}
snapshot.forEach(doc=> {
locList.push(doc.data());
})
}
if (sortformat == 'name'){
// will filter by the type of location, and then sort by alphab
var snapshot = await firebase.firestore().collection('Locations').where(
"category", "==", type).orderBy('name','asce').get();
// this is for All category, it will display all locations
if (type == 'All'){
var snapshot = await firebase.firestore().collection('Locations').orderBy('name','desc').get()
}
if (snapshot.empty){
console.log('No matching documents');
return;
}
snapshot.forEach(doc=> {
locList.push(doc.data());
})
}
}
return filterbytype().then(()=>{
console.log(locList)
return locList;
})
// filterbytype()
}
有问题的部分是排序格式是名称。
【问题讨论】:
-
很难说你的代码为什么不起作用。您可以编辑您的问题以显示:1)您从 Firebase 控制台查询的文档的屏幕截图吗? 2) 处理
snapshot并打印(错误)结果的代码? -
@FrankvanPuffelen 嗨弗兰克,我刚刚更新了我的问题,如您所见,结果没有正确排序名称。
-
感谢您的更新。我仍然缺少#2 的代码,不幸的是这可能是相关的。我还立即注意到您的日志输出将
rating显示为一个数字,但在数据库的屏幕截图中它存储为一个字符串。将数字存储为字符串是导致排序问题的常见原因,因为字符串是按 lexicographically 排序的。 -
@FrankvanPuffelen 嗨弗兰克,我刚刚更新了我的完整代码。按评级排序工作正常,但按字母顺序排序时不起作用。看起来是从 Z 到 A 而不是 A 到 Z
-
这将与此订单子句匹配:
orderBy('rating','desc'),不是吗?
标签: node.js firebase react-native google-cloud-firestore