无法对mongoose查询进行排序

3

注意

在发布此问题前,我已经查看了其他答案,所以希望在这里得到帮助。

Mongoose模型:

请注意保留原有的HTML标签。
const projectSchema = new mongoose.Schema({
  user: { type: String, required: true },
  profile: {
    type: mongoose.Schema.Types.ObjectId,
    required: true,
    ref: 'Profile'
  },
  title: { type: String, required: true },
  image: { type: String },
  description: { type: String, required: true, minlength: 300, maxlength: 3000 },
  comments: [{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Comment'
  }],
  state: { type: Boolean, default: true },
  requests: [{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Request'
  }],
  createdAt: { type: Date, default: Date.now() }, // <== created at

查询:


const projects = await Project.find({
      state: true
    })
      .limit(10)
      .sort({ createdAt: -1 }) // <== have tried +1 and 
                               // also ({ date: -1 }), 
                               // it returns in ascending order
    return res.send(projects || [])

我尝试过将1替换为+1和({ date: -1}),但是它会按升序发送。我希望最新的项目在数组顶部。

你的查询看起来很好,{ createdAt: -1 } 是正确的,你将会按照降序获取记录。 - turivishal
1个回答

5

我成功解决了这个问题。在设置限制之前,我需要先对其进行排序。

const projects = await Project.find({
      state: true
    })
      .sort({ createdAt: -1 })  // here 
      .limit(10)
    return res.send(projects || [])

尝试复现此问题,但无论我在哪里使用 .limit() 都能正常工作 - 很有趣。 - eol
@eol 你说得对,无论我们是先使用限制还是先排序,都没有关系。 - turivishal
那么问题是什么?我有点困惑 :) - eol

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接