Javascript 使用查询的Cloud Firestore不区分大小写排序
我尝试使用OrderBy从CloudFireStore读取排序数据。 和Firestore按以下顺序返回数据: AAAJavascript 使用查询的Cloud Firestore不区分大小写排序,javascript,firebase,google-cloud-firestore,Javascript,Firebase,Google Cloud Firestore,我尝试使用OrderBy从CloudFireStore读取排序数据。 和Firestore按以下顺序返回数据: AAA BBB aaa bbb 现在,我想要的是如下内容: AAA aaa BBB bbb 我只希望使用排序方式获得此结果,而不是手动排序。 在Firestore中有没有这样的排序方法? 请为我提供一个解决方案 提前感谢。云Firestore中的排序区分大小写。没有使排序忽略大小写的标志 实现用例的唯一方法是将字段存储两次 假设存储“AAA”和“AAA”的字段称为myData。在客户端
BBB
aaa
bbb 现在,我想要的是如下内容: AAA
aaa
BBB
bbb 我只希望使用排序方式获得此结果,而不是手动排序。
在Firestore中有没有这样的排序方法?
请为我提供一个解决方案
提前感谢。云Firestore中的排序区分大小写。没有使排序忽略大小写的标志 实现用例的唯一方法是将字段存储两次 假设存储“AAA”和“AAA”的字段称为
myData
。在客户端代码中,您需要存储第二个名为myData\u insensitive
的字段,其中存储数据的不区分大小写副本
DocA:
-> myData = 'AAA'
-> myData_insensitive = 'AAA'
DocB:
-> myData = 'aaa'
-> myData_insensitive = 'AAA'
DocC:
-> myData = 'BBB'
-> myData_insensitive = 'BBB'
DocD:
-> myData = 'bbb'
-> myData_insensitive = 'BBB'
现在您可以通过myData\u
查询和/或订购,但显示myData
这方面有两件有趣的事情:
caseFoldNormalize = function (s){
return s.normalize('NFKC').toLowerCase().toUpperCase().toLowerCase()
};
caseFoldDoc = function(doc, field_options) {
// Case fold desired document fields
if (field_options != null) {
for (var field in field_options) {
if (field_options.hasOwnProperty(field)) {
switch(field_options[field]) {
case 'case_fold':
if (doc.hasOwnProperty(field) && Object.prototype.toString.call(doc[field]) === "[object String]") {
doc[field.concat("_insensitive")] = caseFoldNormalize(doc[field])
}
break;
}
}
}
}
return doc;
}
var raw_document = {
name: "Los Angeles",
state: "CA",
country: "USA",
structure: 'Waſſerſchloß',
message: 'quıt quit' // Notice the different i's
};
var field_options = {
name: 'case_fold',
country: 'case_fold',
structure: 'case_fold',
message: 'case_fold'
}
var firestore_document = caseFoldDoc(raw_document, field_options);
db.collection("cities").doc("LA").set(firestore_document).then(function() {
console.log("Document successfully written!");
}).catch(function(error) {
console.error("Error writing document: ", error);
});
这将在Cloud Firestore中为您提供一个包含以下字段的文档:
{
"name": "Los Angeles",
"state": "CA",
"country": "USA",
"structure": "Waſſerſchloß",
"message": "quıt quit",
"name_casefold": "los angeles",
"country_casefold": "usa",
"structure_casefold": "wasserschloss",
"message_casefold": "quit quit"
}
要处理较旧的浏览器,您可以在中看到一个解决方案。您也可以在获得结果后手动执行此操作:
docArray.sort((a, b) => {
if (a.myData.toLowerCase() < b.myData.toLowerCase()) {
return -1;
}
if (a.myData.toLowerCase() > b.myData.toLowerCase()) {
return 1;
}
return 0;
});
docArray.sort((a,b)=>{
if(a.myData.toLowerCase()b.myData.toLowerCase()){
返回1;
}
返回0;
});
甚至更短:docArray.sort((a,b)=>{return a.myData.localeCompare(b.myData)})
这适用于小集合,但如果您有很多集合,并且在查询中使用分页,则结果应该在返回到客户端之前排序。我使用firebase越多,我越不想使用它,这么简单的事情怎么又变得如此复杂