Miku
Miku

Reputation: 157

Mongoose reverse order of some elements picked out of entire list

Currenty in Messages collection, I have have items like [1,2,3,4,5,6,7 ... 20].

If I code as following:

let order = "desc";
let sortBy = "_id";
const messages = await Message.find({ channel: channelID })
      .sort([[sortBy, order]])

Then "const messages" gets something like [20,19,18,17,16].

But I want it to be [16,17,18,19,20] after receiving from mongoose find function, without manually reverse this array.

I tried to set let order = "asc"; but it then gives me [1,2,3,4,5]

How do I get [16,17,18,19,20] directly from mongoose query without manually reverse the order?

Upvotes: 0

Views: 374

Answers (1)

luckongas
luckongas

Reputation: 1799

The correct MongoDB syntax would be

db.Message.find({ channel: channelID })
      .sort({ "_id": 1 })

So in JS

const messages = await Message.find({ channel: channelID })
      .sort({ "_id", 1})

Or if you want to keep _id and 1 out of the query

const order = 1;
const sortBy = "_id";

const orderQuery = {};
orderQuery[sortBy] = order ;

const messages = await Message.find({ channel: channelID })
      .sort(orderQuery)

Any issue let me know

Upvotes: 1

Related Questions