首页 > 解决方案 > 在带有 mongodb 的 azure 函数应用程序中使用持久函数

问题描述

我有一个 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();
    }
});

标签: node.jsmongodbazure-functions

解决方案


试试下面的代码来检查你是否可以先连接到数据库。使用 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();
    }
  );
});

在此处输入图像描述

尝试console.log(timeSched);输出timeSched。此外,当您执行console.log(timeSched.length);,timeSched并没有被授予价值。这就是你得到的原因0


推荐阅读