0

Like you know {$in: {_id: []}} doesn't keep order.

I want to use Async.js for this purposes.

For example

const ids = [3,1,2]; // Initial ids, I get it from aggregation
const documents = [{_id:1}, {_id:2}, {_id: 3}]; // That's I get from MongoDB
const result = [{_id:3}, {_id: 1}, {_id: 2}] // That's I need 

How can I perform this with Async.js? I'm using mongoose.js with mongoose-fill which don't work with aggregation

Alexander
  • 31
  • 2
  • whats wrong with collecting all results and then using just JS sortBy any parameter that you like? – Mykola Borysyuk Nov 01 '16 at 17:57
  • I don't exactly understand what did you mean. Like I think, I have to write two loops: var result = []; for(var i=0;i – Alexander Nov 01 '16 at 18:05
  • Check my answer. Simple always better. Maybe i miss understand your question. But based on what i see you need to sort results of all queries. Which can be done just fine in JS. But if you want to query each id one by one and then sort array. I would recommend just use one query. This is increase performance by a lot. – Mykola Borysyuk Nov 01 '16 at 18:09
  • I have already received documents from MongoDB, but order not match parameters. I want to sort documents exact the same as parameter array. – Alexander Nov 01 '16 at 18:12
  • Have you seen https://stackoverflow.com/questions/22797768/does-mongodbs-in-clause-guarantee-order? Lots of options in the answers there. – JohnnyHK Nov 01 '16 at 18:13
  • @JohnnyHK thx, I found solution. Very appreciate.. – Alexander Nov 01 '16 at 19:29

1 Answers1

1

You dont need async here. Natural JavaScript sort will help you with this.

To query mongodb just use query like this

{_id : {$in: [1,2,3]}} ;

When you receive results like this

const documents = [{_id:1}, {_id:2}, {_id: 3}];

Now you can just run simple sort

let result = documents.sort((a, b) => a._id < b._id);

console.log(result);

Will output sort by id descending order.

[{_id:3}, {_id: 2}, {_id: 1}];

Hope this helps.

Mykola Borysyuk
  • 3,373
  • 1
  • 18
  • 24
  • No, no, no.. I want to map documents with ids. Example with a post not correct. I found solution [this](http://stackoverflow.com/a/32385762/7054633) – Alexander Nov 01 '16 at 18:56