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.
Have you looked into mongojs (https://github.com/gett/mongojs) ? I use this for my node apps and it works nicely (I also use expressjs). You can do a simple find and sort by with the following syntax:
db.test.find().sort({name:1}, function(error, tuples) { console.log(tuples) });
Can't you just do the same thing to the output of your call?:
operation.call(collection, params.selector, params.fields, params.options,
function(error, result){
...
}
).sort({field: 1});
If the sort can only be applied to the results of find
and not findOne
, then it's a bit more complicated:
var operation = (params.options.one) ? collection.findOne : function() {
var findResults = collection.find.apply(this, [].slice.call(arguments));
return findResults.sort({field: 1});
};
(That last is entirely untested, of course, but looks like it should be close.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With