[英]Node.js sorting array with findOne
我正在嘗試按時間降序對 Mongodb、 Image
元素中的數組進行排序。 日期位於數組內。 這是當前的輸出:
"address": "Product Address 1",
"town": "Brighton",
"Image": [
{
"price": 1021,
"time": "2020-09-13T12:06:34.079Z"
},
{
"price": 1022,
"time": "2020-09-13T12:18:50.270Z"
},
{
"price": 1023,
"time": "2020-09-13T12:37:22.499Z"
}
]
我首先需要的是以下元素,然后是剩余的兩個數組元素:
{
"price": 1023,
"time": "2020-09-13T12:37:22.499Z"
}
我的代碼是:
dbProduct.findOne({
productId: productId
},{'image.token':0}).then(dbRes => {
if (dbRes !== null) {
res.apiSuccess({
town: dbRes.town,
county: dbRes.county,
postCode: dbRes.postCode,
image: dbRes.image
});
} else {
res.apiError(messages.product.not_found);
}
任何幫助表示贊賞。 謝謝
試試這個,看看它是否有幫助
dbProduct.findOne({
productId: productId
},{'image.token':0},{sort: {image.$.time: -1 }}).then(dbRes => {
if (dbRes !== null) {
res.apiSuccess({
town: dbRes.town,
county: dbRes.county,
postCode: dbRes.postCode,
image: dbRes.image
});
} else {
res.apiError(messages.product.not_found);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.