【问题标题】:Node.js sorting array with findOneNode.js 使用 findOne 对数组进行排序
【发布时间】:2021-01-03 13:38:12
【问题描述】:

我正在尝试按时间降序对来自 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);
        }

任何帮助表示赞赏。谢谢

【问题讨论】:

  • 您具体要问什么?如何从现有数据中创建可排序的时间?如何使用 findOne 的来源进行本地排序?
  • 你能发布确切的预期结果吗?我对您发布的示例以及“剩余的两个元素”感到有点困惑
  • 我想反转显示的 3 个图像元素(价格、时间)。所以第一个图片元素需要是{"price": 1023, "time": "2020-09-13T12:37:22.499Z"},第二个{"price": 1022, "time": "2020-09 -13T12:18:50.270Z"} ..
  • 尝试使用.sort() 方法。如果您只希望得到一个结果,.limit() 方法也可能会派上用场。
  • findOne() 只返回一条记录,所以不确定 sort() 是否可以在这里工作。它的数组中的数据我需要重新排序

标签: javascript node.js mongodb


【解决方案1】:

试试这个,看看是否有帮助

 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);
        }

【讨论】:

猜你喜欢
  • 2014-02-22
  • 2021-04-04
  • 1970-01-01
  • 2019-12-18
  • 2021-11-02
  • 2012-11-14
  • 2014-12-11
  • 2016-05-05
相关资源
最近更新 更多