首页 > 解决方案 > Mongoose 如何对 .populate 字段进行排序

问题描述

我正在使用用户/文章配置文件系统。我一直在使用.populate()来呈现帖子,但我无法按创建日期对文章进行排序。

我使用createdAt变量作为对显示的帖子进行排序的主要方式。

以供参考:

router.get('/:id', async (req, res) => {
    const user = await User.findById(req.params.id, function(error) {
        if(error) {
            req.flash("error", "something went wrong")
            res.redirect("/");
        }
    }).populate('articles')

    res.render('users/show',{
        user: user
    });

和 article.js:

const ArticleSchema = new mongoose.Schema({
  title: {
    type: String,
    required: true
  },

  author: {
    type: String
  },

  markdown: {
    type: String,
    required: true
  },

  createdAt: {
    type: Date,
    default: Date.now
  },

  slug: {
    type: String,
    required: true,
    unique: true
  },

  sanitizedHtml: {
    type: String,
    required: true
  },

  img: {
    type: String
  },

  type:{
    type: String
  },

  user : { type: Schema.Types.ObjectId, ref: 'User' },

}, {timestamps: true});

提前感谢大家的帮助。

标签: node.jsmongoose

解决方案


有一个名为populate的属性options

.populate({
  path: 'articles',
  options: { sort: { createdAt: -1 } }
})

推荐阅读