【问题标题】:Mongoose how to sort array of objects returned from queryMongoose如何对查询返回的对象数组进行排序
【发布时间】:2017-08-04 03:34:12
【问题描述】:

我有以下架构:

const userSchema = new Schema({
  local: {
    email: {type: String, unique: true, sparse: true, lowercase: true, trim: true, required: true},
    password: {type: String, required: true},
  },
  username: {type: String, unique: true, lowercase: true, trim: true},
  Items: [{
    name: {type: String, trim: true},
    createdAt: {type: Date, default: Date.now}
  }]
});

我正在使用以下查询来检索所有项目:

User.findById(req.user.id, 'Items -_id', (err, user) => { ... });

返回以下内容:

{ Items: 
   [ 
     { name: 'test1',
       _id: 58c70800a03d09a31bb7fc17,
       createdAt: Mon Mar 13 2017 20:58:40 GMT+0000 (GMT) },
     { name: 'test2',
       _id: 58c70826a03d09a31bb7fc18,
       createdAt: Mon Mar 13 2017 20:59:18 GMT+0000 (GMT) } 
   ] 
}

我的问题是:如何编辑我的 mongoose 查询以返回 Items 数组内的对象,该数组根据 createdAt 属性按降序排序?也就是说,test2 出现在test1 上方。

(一些附加信息,平均每个用户的 items 数组长度为 3-10,并且我使用 Nodejs 作为后端,因此,在应用程序端对数组进行排序是可以忍受的,因为它很小由于 Nodejs 单线程性质,大小或效率太低?),谢谢。

【问题讨论】:

    标签: arrays node.js mongodb sorting mongoose


    【解决方案1】:

    您可以使用aggregation 匹配您的_id,展开Items 数组,执行降序排序并仅投影Items 字段:

    User.aggregate([{
        "$match": {
            "_id": new mongoose.mongo.ObjectId("58c7fa6987200dfc592d088c")
        }
    }, {
        "$unwind": "$Items"
    }, {
        "$sort": {
            "Items.createdAt": -1
        }
    }, {
        "$group": {
            "Items": {
                "$push": "$Items"
            },
            "_id": 1
        }
    }, {
        "$project": {
            "_id": 0,
            "Items": 1
        }
    }], function(err, res) {
        console.log(res);
    })
    

    【讨论】:

    • 此解决方案返回 Items 数组中每个对象的用户 ID,如何从查询结果中排除用户 ID?而且这个查询是否比在客户端使用节点更有效?谢谢
    • 在项目阶段添加"_id":0排除_id。聚合是 mongodb 的一个特性,它比在 nodejs 中做的效率要高得多
    • 非常感谢,是否可以将其格式化为与我原始问题中的输出相同的方式?所以它只是一个包含对象的数组,因为现在它返回一个数组,其中包含每个对象的“Items”键的对象?谢谢
    • 使用$group,查看我的更新答案
    • 返回值是一个数组,其中包含一个对象,该对象包含“项目”中的所有单个对象,但我在问题中提到的原始输出是返回一个对象,该对象指向包含“中的单个对象”的数组项目,我如何编辑您的答案以将其更改为?谢谢
    猜你喜欢
    • 2021-10-02
    • 1970-01-01
    • 2012-03-10
    • 2014-09-28
    • 1970-01-01
    • 1970-01-01
    • 2010-10-12
    • 1970-01-01
    • 2021-10-20
    相关资源
    最近更新 更多