【问题标题】:How to sort array of embedded documents via Mongoose query?如何通过 Mongoose 查询对嵌入文档数组进行排序?
【发布时间】:2012-03-10 02:15:46
【问题描述】:

我正在使用 Mongoose 构建一个 node.js 应用程序,但遇到了与排序嵌入文档相关的问题。这是我使用的架构:

var locationSchema = new Schema({
    lat: { type: String, required: true },
    lon: { type: String, required: true },
    time: { type: Date, required: true },
    acc: { type: String }
})

var locationsSchema = new Schema({
    userId: { type: ObjectId },
    source: { type: ObjectId, required: true },
    locations: [ locationSchema ]
});

我想输出嵌入在 userLocations 文档中的位置,这些位置按时间属性排序。在我从 MongoDb 检索数据后,我目前在 JavaScript 中进行排序,如下所示:

function locationsDescendingTimeOrder(loc1, loc2) {
   return loc2.time.getTime() - loc1.time.getTime()
}

LocationsModel.findOne({ userId: theUserId }, function(err, userLocations) { 
   userLocations.locations.sort(locationsDescendingTimeOrder).forEach(function(location) {
      console.log('location: ' + location.time);
   }
});

我确实阅读了 Mongoose 提供的排序 API,但我不知道它是否可用于对嵌入式文档数组进行排序,如果可以,它是否是一种明智的方法以及如何将其应用于此问题。谁能帮帮我好吗?

在此先感谢和欢呼, 乔治

【问题讨论】:

    标签: node.js mongoose


    【解决方案1】:

    这也可以使用猫鼬排序 API 来完成。

    LocationsModel.findOne({ userId: theUserId })
    //    .sort({ "locations.time": "desc" }) // option 1
        .sort("-locations.time")              // option 2
        .exec((err, result) => {
            // compute fetched data
        })
    

    Sort by field in nested array with Mongoose.js

    这个答案中也提到了更多方法

    Sorting Options in mogoose

    Mongoose Sort API

    【讨论】:

      【解决方案2】:

      你做对了,乔治。您的其他选择是首先在嵌入时按时间对位置进行排序,或者采用更传统的非嵌入路线(或最小嵌入路线,以便您可能嵌入一组 id 或其他东西,但您实际上是在查询位置分开)。

      【讨论】:

      • 谢谢杰德。我最终使用了您提出的方法 - 在嵌入时对位置进行排序。对我来说很好。
      • 这也是我的问题,但是如何在嵌入时对嵌入的文档进行排序?
      • 我想通了。您可能的意思是,通过 .push 或 .unshift 添加新文档时,它将被正确定位。
      猜你喜欢
      • 2016-09-30
      • 2012-08-26
      • 2023-03-16
      • 2019-04-11
      • 2017-08-04
      • 1970-01-01
      • 2016-06-28
      • 2016-09-23
      • 2012-02-11
      相关资源
      最近更新 更多