Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How sort results in a nodejs - mongodb search, but, by calling a dynamic method

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.

like image 422
larrytron Avatar asked Jul 19 '12 11:07

larrytron


2 Answers

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) });
like image 171
Alex Roe Avatar answered Oct 30 '22 14:10

Alex Roe


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.)

like image 28
Scott Sauyet Avatar answered Oct 30 '22 14:10

Scott Sauyet