【问题标题】:mongoose populate sort _ Mongoose Node.js猫鼬填充排序_猫鼬Node.js
【发布时间】:2019-09-16 13:36:19
【问题描述】:

我有两个模式代表我的帖子和类别文档。我正在尝试使用 category.order 属性对我的帖子进行排序。 order 属性是一个数字字段。

const postSchema = mongoose.Schema({
    title: {
        type: String,
        max: 200,
    },
    body: {
        type: String,
        max: 10000,
    },
    categories: {
        type: mongoose.Schema.ObjectId,
        ref: 'Category',
        required: true
    }
})
module.exports = mongoose.model('Post', postSchema);


const categorySchema = mongoose.Schema({
    name: {
        type: String,
        max: 30,
        required:true
    },
    order: {
        type: Number,
        unique: true
    },
})
module.exports = mongoose.model('Category', categorySchema);

我知道排序只适用于数字字段。我搜索了很多关于 web 和 StackOverflow 中的类似问题,甚至是 mongoose 文档。但我的查询不起作用。它让我的帖子回来了,但排序顺序不起作用。 查询:

Post.find({}).populate({path:'categories', select:'order', options:{sort:{order:1}}})

【问题讨论】:

    标签: node.js mongodb mongoose aggregation-framework


    【解决方案1】:

    很好填充不会sort 根/外部文档。在populate 中传递的选项仅在sorts 内部引用的文档中。您必须在此处使用aggregation 对父文档进行排序,与populate 查询相比,$lookup 可以做得更好。

    Post.aggregate([
      { '$lookup': {
        'from': 'categories',
        'let': { 'categories': '$categories' },
        'pipeline': [
          { '$match': { '$expr': { '$eq': ['$_id', '$$categories'] }}},
          { '$project': { 'order': 1 }}
        ],
        'as': 'categories'
      }},
      { '$unwind': '$categories' },
      { '$sort': { 'categories.order': 1 }}
    ])
    

    【讨论】:

    • tnx 用于在短时间内回复,我一直在编辑我的代码问题部分关于模式。我试过你的查询,但带有空数组。
    • 对不起,我弄错了。现在更新了我的答案。请再试一次
    • tnx 你是我的救星。另一个问题。是排序可以接受:[“acs”,“dec”]不是我的意思是数字
    • 不,为什么你需要'asc'和'dsc'。 1 和 -1 的作用相同
    猜你喜欢
    • 2016-08-17
    • 2015-07-13
    • 2016-10-10
    • 2020-11-02
    • 2020-07-25
    • 2021-05-03
    • 2021-01-09
    • 2018-06-01
    相关资源
    最近更新 更多