[英]Fetched sorted API data(NodeJs &Mongoose) not getting displayed in sorted order when try display in Angular UI
我试图在后端进行排序并通过 postman 进行测试,我得到了排序。
const locationInfo = await locationDetails.find(query).sort({sectionName:1});
res.json(locationInfo);
[
{ //some other keys &values
"sectionName": "Closet",
},
{
"sectionName": "Dining",
},
{
"sectionName": "Kitchen",
},
{
"sectionName": "Other",
},
{
"sectionName": "Refrigerator",
}
]
REST调用存储结果之后,
this.result=data;
但是当我尝试在 UI 上显示相同的结果数据时,它没有按排序顺序显示,也没有在控制台中检查,结果数据顺序也发生了变化。
控制台数据
[{
sectionName: "Refrigerator",
},
{
sectionName: "Kitchen",
},
{
sectionName: "Dining",
},
{
sectionName: "Closet",
},
{
sectionName: "Other",
}]
注意:也尝试从 .ts 文件排序,但它不起作用。
this.result.sort(function(a,b){a.sectionName-b.sectionName});
如果有任何帮助将不胜感激。 谢谢!
SectioName
不是 MongoDB 对返回结果进行排序的有效标准。 在这种情况下,MongoDB 不知道如何排序。
以下是 MongoDB 文档中有关cursor.sort()
的示例:
db.restaurants.insertMany( [
{ "_id" : 1, "name" : "Central Park Cafe", "borough" : "Manhattan"},
{ "_id" : 2, "name" : "Rock A Feller Bar and Grill", "borough" : "Queens"},
{ "_id" : 3, "name" : "Empire State Pub", "borough" : "Brooklyn"},
{ "_id" : 4, "name" : "Stan's Pizzaria", "borough" : "Manhattan"},
{ "_id" : 5, "name" : "Jane's Deli", "borough" : "Brooklyn"},
] );
# The following command uses the sort() method to sort on the borough field:
db.restaurants.find().sort( { "borough": 1 } )
文档按 borough 按字母顺序返回,但那些具有 borough 重复值的文档的顺序在多次执行中可能不同。
.sort
最适用于数值。 如果您控制后端并且能够更改数据在数据库中的存储方式。 我建议您为创建日期创建一个字段,或者只是一个索引来指示项目的顺序。
假设您的文档如下所示:
# Doc 1
{
sectionName: "Refrigerator",
order:1
}
# Doc 2
{
sectionName: "Refrigerator",
order:2
}
然后你可以做
const locationInfo = await locationDetails.find(query).sort({order:1});
这将返回您使用 order 字段排序的文档,并且顺序将是一致的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.