如何排序结果在一个nodejs - mongodb搜索,但是通过调用一个动态方法 [英] How sort results in a nodejs - mongodb search, but, by calling a dynamic method

查看:111
本文介绍了如何排序结果在一个nodejs - mongodb搜索,但是通过调用一个动态方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



在我的一个js文件中,我有一个通用的方法来调用一个find或findOne操作,以从mongodb集合中检索我需要的东西,如下所示:



它对我来说很好。



但是现在,我需要对结果进行排序,据我所知,Mongodb使用sort方法来实现这一点。

  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,
函数(错误,结果){
if(error){
...
} else {
...
}
}
);
}
});

在一个简单的查询中,这应该是这样的:
例如:

  collection.find()。sort({field:1}),

我不知道如何调用sort方法,这样做我的通用方式。



任何想法?



谢谢。

解决方案

我找到了解决方案。



似乎toArray丢失,否则不起作用。

  operation.call(collection,params.selector,params.fields,params.options,function(error,result){
if (错误){
callback(error);
} else {
result.sort(params.sort).toArray(function(error,items){
...
}
}

我希望这将是有帮助的


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.

解决方案

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

这篇关于如何排序结果在一个nodejs - mongodb搜索,但是通过调用一个动态方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆