質問

I have a little problem to display a result set in original order. My mongoose "query" is simply :

myCollection.find({}, null, {sort: {weight: 1}}, function (err, res) {
    //etc...
});

The log of res is good, my result is correctly sorted by weight asc.

I display the result with a forEach loop in an ejs template like this :

<% res.forEach(function(r) { %>
    <%= r.weight %>
<% }) %>

And it displays my result in a "pseudo-random" order ... e.g : 2,3,4,1,9,10,6 ...

In my Schema, weight param is a Number

weight          : { type: Number, default: 0, required: false }

UPDATE :

I execute another query on the result, in a loop like that :

newResult = [];
async.each(res, function(r, callback) {
    // some actions with r ...
    newResult.push(r);
}, ....);

I construct a new list of objects in my loop and it's THIS list who is send to the view to display elements.

I think js reorder the array ...

Is it possible to keep the original order ?

Tks. Appreciate your help. C.

役に立ちましたか?

解決 2

Thank you @nabeel, your answer led me on the right way :)

The solution to reorder an array of objects with async is async.sortBy()

async.sortBy(newResult, function(n, callback){
    callback(err, n.sort.criteria);
}, function(err, results){
    callback(null, results);
});

results is now the sorted array

他のヒント

I'm not sure why it's not working for you. Please try like this...

myCollection.find()
  .sort("weight")
  .exec(function (err, res) {
    //etc...
});

UPDATE

async.each is an asynchronous function which means that the callbacks can be out of order. So if you don't want to lose the order of the array you should either use a simple for loop OR you can re-sort the array after async.each has finished.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top