在Mongoose中使用查询查询并对具有多个条件和排序数据更改的数据进行排序

时间:2015-12-28 06:30:49

标签: node.js mongodb mongoose

//Code for one condition of sort

var query = SbAggregate.find({
    MemberClassType: memberType,
    CreatedDate: { "$gte": new Date(start), "$lte": new Date(end) }
}).sort({ field1: -1, field2: -1 });

query.exec(function (err, doc) {
    //data
}

//In same method doing another query
var query = SbAggregate.find({
    MemberClassType: memberType,
    CreatedDate: { "$gte": new Date(start), "$lte": new Date(end) }
}).sort({ field2: -1 });

query.exec(function (err, doc) {
    //data
}

//Same method another condition for sort
var query = SbAggregate.find({
    MemberClassType: memberType,
    CreatedDate: { "$gte": new Date(start), "$lte": new Date(end) }
}).sort({ field3: -1 });

query.exec(function (err, doc) {
    //data
}

通过变量动态设置条件,并在多个sortin条件下使用多个查询调用相同的方法。

2 个答案:

答案 0 :(得分:1)

sort参数是一个简单的对象,您可以按照自己的方式构建它。这是一个例子:

//Code for one condition of sort
var sortParam1 = { };
var sortParam2 = { };
var sortParam3 = { };

if (someCondition) {
    sortParam1 = { field1: -1, field2: -1 }
} else if (someOtherCondition) {
    sortParam2 = { field2: -1 };
} else if (anotherCondition) {
    sortParam3 = { field3: -1 };
}

var query = SbAggregate.find({
    MemberClassType: memberType,
    CreatedDate: { "$gte": new Date(start), "$lte": new Date(end) }
}).sort(sortParam1);

query.exec(function (err, doc) {
    //data
}

//In same method doing another query
var query = SbAggregate.find({
    MemberClassType: memberType,
    CreatedDate: { "$gte": new Date(start), "$lte": new Date(end) }
}).sort(sortParam2);

query.exec(function (err, doc) {
    //data
}

//Same method another condition for sort
var query = SbAggregate.find({
    MemberClassType: memberType,
    CreatedDate: { "$gte": new Date(start), "$lte": new Date(end) }
}).sort(sortParam3);

query.exec(function (err, doc) {
    //data
}

答案 1 :(得分:0)

你说你想要这样的东西吗?

//sortFields is our sort object
//{field1: -1, field2: -1}, {field3"}, etc
function getData(sort) {
  var query = SbAggregate.find({
    MemberClassType: memberType,
    CreatedDate: {
      "$gte": new Date(start),
      "$lte": new Date(end)
    }
  }).sort(sort);

  query.exec(function(err, doc) {
      return doc;
    }
  }
}

调用它看起来像这样

getData({field1: -1, field2: -1});
getData({field2: -1});
//etc

您可以传入任何对象并将其传递给查找查询。