无法对猫鼬查询进行排序

时间:2020-10-16 10:42:20

标签: node.js mongodb express mongoose

注意

在发布此信息之前,我还经历了其他答案,因此希望在这里获得帮助。

猫鼬模型:

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}),它以升序发送。 我希望最新的项目在阵列之上。

1 个答案:

答案 0 :(得分:5)

我能够解决它。 在设置限制之前,我需要进行排序。

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