node.js - Mongoose 如何编写带if条件的查询?

标签 node.js mongodb mongoose aggregation-framework mean-stack

假设我有以下查询:

post.getSpecificDateRangeJobs = function(queryData, callback) {
var matchCriteria = queryData.matchCriteria;
var currentDate = new Date();
var match = { expireDate: { $gte: new Date(currentDate.getFullYear(), currentDate.getMonth(), currentDate.getDate()) } };
if (queryData.matchCriteria !== "") {
  match = {
    expireDate: { $gte: new Date(currentDate.getFullYear(), currentDate.getMonth(), currentDate.getDate()) },
    $text: { $search: matchCriteria }
  };
}
var pipeline = [
  {
    $match: match
  },
  {
    $group: {
      _id: null,
      thirtyHourAgo: {
        $sum: {
          $cond: [
            {
              $gte: [
                "$publishDate",
                new Date(queryData.dateGroups.thirtyHourAgo)
              ]
            },
            1,
            0
          ]
        }
      },
      fourtyEightHourAgo: {
        $sum: {
          $cond: [
            {
              $gte: [
                "$publishDate",
                new Date(queryData.dateGroups.fourtyHourAgo)
              ]
            },
            1,
            0
          ]
        }
      },
      thirtyDaysAgo: {
        $sum: {
          $cond: [
            {
              $lte: [
                "$publishDate",
                new Date(queryData.dateGroups.oneMonthAgo)
              ]
            },
            1,
            0
          ]
        }
      }
    }
  }
];
var postsCollection = post.getDataSource().connector.collection(
    post.modelName
);
postsCollection.aggregate(pipeline, function(err, groupByRecords) {
  if (err) {
    return callback("err");
  }
  return callback(null, groupByRecords);
});
};

我想做的是: 1- 检查 queryData.dateGroups.thirtyHourAgo 是否存在并具有值(value),然后只在查询中添加相关的匹配子句(仅过去 30 小时的帖子计数)。 2- 检查 queryData.dateGroups.fourtyHourAgo 是否存在,然后添加相关查询部分(过去 30 小时和过去 ​​48 小时前的帖子计数)。 3 和 queryData.dateGroups.oneMonthAgo 相同(过去 30 小时、48 小时和过去一个月的帖子数)。

我需要类似 Mysql 的 if 条件来检查变量是否存在且不为空,然后包含一个查询子句。有可能吗?

我的样本数据是这样的:

/* 1 */
{
"_id" : ObjectId("58d8bcf01caf4ebddb842855"),
"vacancyNumber" : "123213",
"position" : "dsfdasf",
"number" : 3,
"isPublished" : true,
"publishDate" : ISODate("2017-03-11T00:00:00.000Z"),
"expireDate" : ISODate("2017-05-10T00:00:00.000Z"),
"keywords" : [ 
    "dasfdsaf", 
    "afdas", 
    "fdasf", 
    "dafd"
],
"deleted" : false
}

/* 2 */
{
"_id" : ObjectId("58e87ed516b51f33ded59eb3"),
"vacancyNumber" : "213123",
"position" : "Software Developer",
"number" : 4,
"isPublished" : true,
"publishDate" : ISODate("2017-04-14T00:00:00.000Z"),
"expireDate" : ISODate("2017-05-09T00:00:00.000Z"),
"keywords" : [ 
    "adfsadf", 
    "dasfdsaf"
],
"deleted" : false
}

/* 3 */
{
"_id" : ObjectId("58eb5b01c21fbad780bc74b6"),
"vacancyNumber" : "2432432",
"position" : "Web Designer",
"number" : 4,
"isPublished" : true,
"publishDate" : ISODate("2017-04-09T00:00:00.000Z"),
"expireDate" : ISODate("2017-05-12T00:00:00.000Z"),
"keywords" : [ 
    "adsaf", 
    "das", 
    "fdafdas", 
    "fdas"
],
"deleted" : false
}

/* 4 */
{
"_id" : ObjectId("590f04fbf97a5803636ec66b"),
"vacancyNumber" : "4354",
"position" : "Software Developer",
"number" : 5,
"isPublished" : true,
"publishDate" : ISODate("2017-05-19T00:00:00.000Z"),
"expireDate" : ISODate("2017-05-27T00:00:00.000Z"),
"keywords" : [ 
    "PHP", 
    "MySql"
],
"deleted" : false
}

假设我的应用程序界面中有三个链接: 1- 30 小时前的帖子。 2- 48 小时前的帖子。 3- 最后一个月的帖子。

现在,如果用户点击第一个链接,我应该控制只对 30 小时前的帖子进行分组,但是如果用户点击第二个链接,我应该准备查询以对 30 小时和 48 小时的帖子进行分组,如果用户单击第三个链接,我应该为所有这些做好准备。

我想要这样的东西:

 var pipeline = [
  {
    $match: match
  },
  {
    $group: {
      _id: null,
      if (myVariable) {
        thirtyHourAgo: {
          ........
          ........
        }
      } 
      if (mysecondVariable) {
        fortyEightHourAgo: {
          ........
          ........
        }
      }

最佳答案

您可以使用 javascript 根据您的查询参数动态创建 json 文档。

更新后的函数看起来像

post.getSpecificDateRangeJobs = function(queryData, callback) {

  var matchCriteria = queryData.matchCriteria;
  var currentDate = new Date();

  // match document
  var match = {
    "expireDate": {
      "$gte": currentDate 
    }
  };

  if (matchCriteria !== "") {
    match["$text"]: {
      "$search": matchCriteria
    }
  };

  // group document
  var group = {
    _id: null
  };

  // Logic to calculate hours difference between current date and publish date is less than 30 hours.

  if (queryData.dateGroups.thirtyHourAgo) {
    group["thirtyHourAgo"] = {
      "$sum": {
        "$cond": [{
            "$lte": [{
              "$divide": [{
                "$subtract": [currentDate, "$publishDate"]
              }, 1000 * 60 * 60]
            }, 30]
          },
          1,
          0
        ]
      }
    };
  }

  // Similarly add more grouping condition based on query params.

  var postsCollection = post.getDataSource().connector.collection(
    post.modelName
  );

  // Use aggregate builder to create aggregation pipeline.

  postsCollection.aggregate()
    .match(match)
    .group(group)
    .exec(function(err, groupByRecords) {
      if (err) {
        return callback("err");
      }
      return callback(null, groupByRecords);
    });

};

关于node.js - Mongoose 如何编写带if条件的查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43889978/

相关文章:

javascript - 对象数组排序不起作用

node.js - Mongoose 模型 - 包括 GridFS 图像引用

javascript - 将 NodeJS 与 Express 3.x 和 Jade 模板一起使用是否可以只为先前呈现的列表重新呈现一个项目?

node.js - mongoose 7.0.3 使用运算符 $and 严格搜索日期

node.js - Mongoose id 函数返回 null

node.js - 避免 Node.js Web 应用程序中的竞争条件

javascript - 我如何保证在我的应用程序中一次性使用 gulp?

带有条件group by语句的MongoDB查询

node.js - Mongoose :不允许更新特定字段

node.js - Passport-Facebook 不提供电子邮件,即使它在范围内