Mongoose:按论坛帖子

时间:2016-11-12 23:08:12

标签: node.js mongodb sorting express mongoose

我有以下对象

    let threadSchema = mongoose.Schema({
  author: {
    type: mongoose.Schema.Types.ObjectId,
    required: true,
    ref: 'User'
  },

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

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

  id: {
    type: Number,
    required: true,
    unique: true
  },

  answers: [{
    type: mongoose.Schema.Types.ObjectId,
    default: [],
    ref: 'Answer'
  }]
})

就像你可以看到的,一组Answer对象:

let answerSchema = mongoose.Schema({
  thread: {
    type: mongoose.Schema.Types.ObjectId, // to article
    required: true,
    ref: 'Thread'
  },

  author: {
    type: mongoose.Schema.Types.ObjectId,  // to user
    required: true,
    ref: 'User'
  },

  creationDate: {
    type: Date,
    required: true
  },

  content: {
    type: String,
    required: true
  }
})

我想要做的是,在对数据库的mongoose查询中,按照最新(最新)答案的线程对线程进行排序。

我尝试了一些愚蠢的事情:

Thread

  .find()
  .populate('answers')
  .sort('answers.creationDate')
  .then((threads) => {
    console.log(threads)
  })

但没有运气。任何具有适当专业知识的人都可以以正确的方式指导我并告诉我,我正在尝试做的是什么? 在此先感谢:)

1 个答案:

答案 0 :(得分:0)

如果要在线程内对Answers子文档数组进行排序,请尝试在排序步骤中进行排序

Thread 
  .find()
  .populate({ path: 'answers', options: { sort: { 'creationDate': : -1 } } })
  .then((threads) => {
    console.log(threads)
  })