Mongoose how to write a query with if condition?

前端 未结 2 501

Suppose I have the following query:

post.getSpecificDateRangeJobs = function(queryData, callback) {
var matchCriteria = queryData.matchCriteria;
var currentD         


        
相关标签:
2条回答
  • 2021-01-18 01:09

    As I understood, I can suggest you following general query. Modify this according to your need.

    db.getCollection('vacancy')
    .aggregate([{$match: { $and: [ 
    {publishDate:{ $gte: new Date(2017, 4, 13) }} , 
    {publishDate:{ $lte: new Date(2017, 4, 14) }}
    ]} }])
    

    Summary:

    • Used match to filter out result.
    • We are using aggregation Pipeline so you can add more aggregate operators n the pipeline
    • Using $and perform a logical AND because we want to fetch some documents between a give range say 1 day, 2 days or 1 month (change date parameters according to your requirement)
    0 讨论(0)
  • 2021-01-18 01:32

    You can use javascript to dynamically create json document based on your query parameters.

    Your updated function will look something like

    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);
        });
    
    };
    
    0 讨论(0)
提交回复
热议问题