簡體   English   中英

嘗試在 Angular UI 中顯示時,提取的已排序 API 數據(NodeJs &Mongoose)未按排序順序顯示

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM