简体   繁体   English

ZCCADCDEDB567ABAE643E15DCF0974E503Z 如何排序。填充字段

[英]Mongoose How to sort .populate field

I'm work with an user/articles profile system.我正在使用用户/文章配置文件系统。 I have been using the .populate() to render the posts but I cannot get the articles sorted by the date they were created.我一直在使用.populate()来呈现帖子,但我无法按创建日期对文章进行排序。

I am using the createdAt variable as the main way of ordering the posts displayed.我使用createdAt变量作为对显示的帖子进行排序的主要方式。

For reference:以供参考:

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
    });

and the article.js:和 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});

In advance thank you all for the help.提前感谢大家的帮助。

There is a property called options in populate ,populate中有一个名为options的属性,

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM