【发布时间】:2020-10-30 12:10:48
【问题描述】:
我在 NodeJS 中有以下 Azure 函数 作为触发器:IoT Hub 事件。
我需要将消息传输到 cosmos DB。
module.exports = function (context, IoTHubMessage) {
try {
var dbName = "db";
var collectionName = "encodedmessages";
context.log(`JavaScript eventhub trigger function called for message array: ${IoTHubMessage}`);
var mongoClient = require("mongodb").MongoClient;
context.log('MongoClient created');
mongoClient.connect("mongodb://xxx:password==@xxx.mongo.cosmos.azure.com:10255/?ssl=true&replicaSet=globaldb&retrywrites=false&maxIdleTimeMS=120000&appName=@db@",{useNewUrlParser: true, authSource: dbName}, function (err, client) {
if(err){
context.log(`Error occurred while connecting to DB ${err}`)
} else{
context.log('MongoClient connected to DB');
}
var collection = mongoClient.db(dbName).collection(collectionName);
context.log('MongoClient collection retreived');
collection.insertOne(IoTHubMessage, {w: 1});
//collection.insertOne({"testKey": 13.56}, {w: 1});
mongoClient.close();
context.log(`Saved message: ${IoTHubMessage}`);
context.done();
});
} catch (e){
context.log(`Error ${e}`);
}
context.log('Done called');
context.done();
};
我还有一个控制台应用程序将消息发送到运行的 iot 集线器,如下所述: https://docs.microsoft.com/en-us/azure/iot-hub/quickstart-send-telemetry-dotnet
输出如下:
2020-10-30T12:06:41.968 [Information] JavaScript eventhub trigger function called for message array: Test Message
2020-10-30T12:06:41.972 [Information] MongoClient created
2020-10-30T12:06:41.972 [Information] Done called
2020-10-30T12:06:42.026 [Information] Executed 'Functions.ProcessEncodedMessages' (Succeeded, Id=2fcb7fa8-b194-4499-bc39-775aef86aac0, Duration=24606ms)
我真的不明白为什么我没有在这段代码的日志中看到消息:
如果(错误){
context.log(Error occurred while connecting to DB ${err})
} 别的{
context.log('MongoClient 连接到数据库');
}
就像它从未达到那个点,我也没有收到关于连接字符串的任何错误。
【问题讨论】:
-
我相信
insertOne函数会返回一个promise,而您并没有等待它,因此它会在解决promise 之前关闭连接 -
不是 nodejs 语法专家,我该如何解决?
标签: javascript node.js azure-functions azure-cosmosdb azure-iot-hub