Wednesday 21 October 2020

Unable to sort mongoose query

Note

I went through other answers before posting this, so expecting help here.

Mongoose model :

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

Query:

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 || [])

I have tried +1 in place of 1 and also ({ date: -1 }), it sends in ascending order. I want the latest projects to be on top of array.



from Unable to sort mongoose query

No comments:

Post a Comment