如何根据条件从COSMOS DB中选择记录

时间:2017-06-03 11:09:11

标签: javascript sql azure-cosmosdb

我在Azure Cosmos DB中有一个文档。

它包含:

{ "id": "58d56db3b3f730153cab383c", "activityDate": "2017-02-11T19:04:18Z", ... ... }

我要求选择仅超过3天的文件。

我写的: //样本存储程序

function deleteActivitiesBackDate(numberOfDays) {
  var context = getContext();
  var collection = context.getCollection();
  var link = collection.getSelfLink();
  var response = context.getResponse();

 var targetDate = new Date();

 targetDate.setDate(targetDate.getDate() - 3);
 console.log("targetDate is "+targetDate);


  var query = 'SELECT * FROM activities a WHERE a.activityDate < "' + targetDate+ '"';
  var run = collection.queryDocuments(link, query, {}, callback);
  function callback(err, docs) {
    if (err){
        return errorResponse(400, err.message);
    }
    if (docs.length > 0){
        for(var i =0;i<docs.length;i++){
        deleteDoc(docs[i]);
       }
    }else {
        return errorResponse(400, "The document was not found.");
    }
  }

  if (!run) {
      return errorResponse(400, "The document could not be deleted.");
  }

  function deleteDoc(document) {
    var docDeleted = collection.deleteDocument(document._self, function(err, result){
        if (err){
            return errorResponse(400, err.message);
        }
        response.setBody(result);
    });

    if (!docDeleted) {
      return errorResponse(400, "The document could not be deleted.");
    }
  };

  function errorResponse(code,message){
    var errorObj = {};
    errorObj.code = code;
    errorObj.message = message;
    errorObj.date = getDateTime();
    return response.setBody(errorObj);
  } 

  function getDateTime(){
    var currentdate = new Date();
    var dateTime = currentdate.getFullYear() + "-" +(currentdate.getMonth()+1)+ "-" +     currentdate.getDate()+ " "  +currentdate.getHours()+":"+currentdate.getMinutes()+":"+currentdate.getSeconds();
      return dateTime;
    }
}

我该怎么做才能解决问题?

1 个答案:

答案 0 :(得分:1)

我认为您想要将select语句更改为使用.toISOString()函数,如下所示:

var query = 'SELECT * FROM activities a WHERE a.activityDate < "' + targetDate.toISOString()+ '"';

您当前的select语句正在将字符串属性与Date()对象进行比较。

另外,我想你想改变这一行:

targetDate.setDate(targetDate.getDate() - 3);

到此:

targetDate.setDate(targetDate.getDate() - numberOfDays);