node.js - 在带有 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();
}
});
解决方案
试试下面的代码来检查你是否可以先连接到数据库。使用 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
;
推荐阅读
- c++ - 从 std::vector 在 MEX C++ 中创建 MATLAB 数组
- ffmpeg - ffmpeg - 首先编码(交换)与渐进式 -top 1 不粘
- android-studio - 最后添加的图像仅在 recyclerview 中显示
- eclipse-cdt - 安装 Eclipse 4.15 的 CDT 坏了?
- web-deployment - 如何自定义 netlify 网站的社交媒体预览?
- python - 在 PyGame 中更改矩形颜色
- python - 用于测试的临时 MEDIA_ROOT 不起作用
- c# - GetItemLinqQueryable 方法 Cosmos DB SDK v3 与 Azure Cosmos DB 太啰嗦了
- c++ - 如何在一个函数中使用传递给指针的信息,并在另一个函数中输出?
- php - 使用 session_set_cookie_params 销毁会话数据