I have a userModel that has about 5 fields that I would like to be sorted in Ascending or Descending when I find({}) them. Everything I have read from the documentation suggests that this should work but it’s not working.
This query only returns a correct order for the first value e.g firstName and returns a non-sorted result for the rest. These are the different sorting techniques that I’ve tried to implement and all return the same result. if I try to flip to Descending order, the exact same behaviour occurs.
UserModel.find({}).sort({firstName: 'asc', lastName:'asc' ,email:'asc',createdAt:'asc', updatedAt:'asc' })
UserModel.find({}).sort({firstName: 1, lastName:1 ,email:1, createdAt:1 , updatedAt: 1 })
UserModel.find({}).sort("firstName lastName email createdAt updatedAt")
UserModel.find({}).sort("firstName, lastName, email, createdAt, updatedAt")
I Also tried to create an index before sorting but still, only the first field is getting sorted
const UserSchema = new mongoose.Schema(
{
firstName: {
type: String,
required: [true, "Please enter a valid first name."],
},
lastName: {
type: String,
required: [true, "Please enter a valid last name."],
},
email: {
type: String,
required: [true, "Please provide a valid email address."],
unique: true
},
createdAt: {
type: Date,
default: null,
},
updatedAt: {
type: Date,
default: null,
},
)
UserSchema.index({firstName: 1, lastName:1 ,email:1, createdAt:1 , updatedAt: 1 })
export default mongoose.models.User || mongoose.model("User", UserSchema)
What am i doing wrongly?