How sort results in a nodejs - mongodb search, but, by calling a dynamic method
express, javascript, mongodb, node.js
Solution
I've found the solution.
It seems that "toArray" was missing, otherwise does not work.
operation.call(collection, params.selector, params.fields, params.options, function(error, result) {
if (error) {
callback(error);
} else {
result.sort(params.sort).toArray(function(error, items) {
...
}
}
I Hope it will be helpful
Problem
I'm developing a web app in nodejs connected to mongodb via mongo native connector. In one of my js files, I have a generic method to invoke a "find" or "findOne" operation to retrieve whatever I need from a mongodb collection, like this: It works fine for me. But now, I need to sort the results, and as far as I know, Mongodb use the "sort" method to achieve this. ``` collection.ensureIndex(indexedFields, function(error, indexName) { if (error) { callback(error); } else { var operation = (params.options.one) ? collection.findOne : collection.find; operation.call(collection, params.selector, params.fields, params.options, function(error, result){ if (error) { ... } else { ... } } ); } }); ``` In an simple query, this should be like this: For example: ``` collection.find().sort({field : 1}), ``` I don't know how to call "sort" method, doing it im my generic way. Any ideas? Thanks.