在MongoDB中使用Azure Function App中的持久函数

时间:2019-07-19 11:32:43

标签: node.js mongodb azure-functions

我有一个mongoDB,其中包含我的持久功能应运行的时间(例如8:00、9:01、10:20)。现在,我的Orchestrator代码在下面,mongoClient.connect内部没有任何作用。为什么?

const df = require("durable-functions");
const moment = require("moment");
const mongoClient = require("mongodb").MongoClient;

module.exports = df.orchestrator(function*(context) {
    context.log("Getting time schedules in DB");
    var timeSched = [];
    var dbName = <dbName>;
    var collectionName = <collectionName>;

    var query = {id: "1"};
    try{
        mongoClient.connect(<mongoDB_connection_string>,{useNewUrlParser: true, authSource: dbName}, function (err, client) {
//Anything inside this does not log or work
            if(err){
                context.log(`Error occurred while connecting to DB ${err}`)
                return context.done();
            }else{
                context.log('MongoClient connected to DB');
            }
            var collection = client.db(dbName).collection(collectionName);
            collection.find(query).toArray(function(err, result) {
                if (err) throw err;
                for(let i = 0; i < result.length; i++){
                    timeSched.push(result[i].time); //e.g.8:00
                }
                client.close();
//This should log [8:00,9:01,10:01] but it does not log
                context.log(timeSched);
                context.done();
            });
        });
//This logs 0
        context.log(timeSched.length);
        for (let j = 0; j < timeSched.length; j++) {
            const deadline = moment.utc(context.df.currentUtcDateTime).add(3, 'minutes');
            yield context.df.createTimer(deadline.toDate());
            yield context.df.callActivity("ActivityFunction",timeSched[j]);
        }
        context.done();
    }catch(e){
        context.log(`Error ${e}`);
        context.done();
    }
});

1 个答案:

答案 0 :(得分:0)

请尝试下面的代码,以检查是否可以首先连接到DB。使用console.log而不是context.log。

const df = require("durable-functions");
const mongoClient = require("mongodb").MongoClient;
module.exports = df.orchestrator(function*(context) {
  var mongoClient = require("mongodb").MongoClient;
  mongoClient.connect(
    "mongodb://tonytest:78jst6Mh****.documents.azure.com:10255/?ssl=true",
    function(err, client) {
      if (err) {
        console.log(`Error occurred while connecting to DB ${err}`);
        return context.done();
      } else {
        console.log("MongoClient connected to DB");
      }
      client.close();
    }
  );
});

enter image description here

尝试使用console.log(timeSched);输出timeSched。此外,当您执行console.log(timeSched.length);时,timeSched尚未被授予价值。这就是为什么您得到0;