在Mongoose中按数组长度对文档进行排序

时间:2019-06-13 10:43:09

标签: node.js mongodb mongoose mongodb-query aggregation-framework

我有一个简单的帖子架构,其中包含喜欢此帖子的一系列用户ID:

const PostSchema = new Schema({

title:{type: String, required: true},
content:    {type: String, required: true },
tags:       [{type:String}],
author:     {type:mongoose.Schema.Types.ObjectId, ref:"User", required:true},
likes:      [{ type:mongoose.Schema.Types.ObjectId, ref:"User", required:false}],
createTime: {type:Date, default:Date.now}

})

我想对我的文档进行“我的喜欢”计数排序,换句话说,按“我的喜欢”数组长度对我的帖子排序。我尝试了类似的方法,但是没有用:

// @route  GET api/posts

router.get('/',(req, res)=>{

  Post.aggregate([{ $addFields: {likesCount:{$size:"likes"}} }]);
  Post.find()
    .populate('author','name email')
    .sort({likesCount:1})
    .then(posts=> res.json(posts))
    .catch(err=>console.log(err))
  })

我不知道如何正确设置。请任何帮助。预先谢谢你:)

1 个答案:

答案 0 :(得分:1)

您可以使用以下汇总

Post.aggregate([
  { "$lookup": {
    "from": Author.collection.name,
    "let": { "author": "$author" },
    "pipeline": [
      { "$match": { "$expr": { "$eq": [ "$_id", "$$author" ] } } },
      { "$project": { "name": 1, "email": 1 }}
    ],
    "as": "author",
  }},
  { "$unwind": "$author" },
  { "$addFields": { "likesCount": { "$size": "$likes" }}},
  { "$sort": { "likesCount": 1 }}
])