簡體   English   中英

Node.js 使用 findOne 對數組進行排序

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

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