如何排序结果在一个nodejs - mongodb搜索,但是通过调用一个动态方法 [英] How sort results in a nodejs - mongodb search, but, by calling a dynamic method
问题描述
在我的一个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屋!