【发布时间】:2018-10-27 03:31:40
【问题描述】:
我有一个节点函数调用 mongo 来请求一些数据。没有错误,但似乎也没有连接到 mongo 并获取数据。是不是我做的不对?
const MongoClient = require('mongodb').MongoClient;
module.exports = async (context, req) => {
try {
let connectionString = 'mongodb://<username>:<password>@<endpoint>.documents.azure.com:10255/?ssl=true';
context.log('******************** 11 *************************');
MongoClient.connect(connectionString, {uri_decode_auth: true}, function(err, client) {
if (err) {
context.log('Failed to connect');
context.res = { status: 500, body: err.message }
return context.done();
}
context.log('******************** 22 *************************');
client.db("stuff").collection("items").find({}).toArray(function(err, result) {
if (err) {
context.log('Error running query');
context.res = { status: 500, body: err.message }
return context.done();
}
context.log(result);
context.log('******************** 44 *************************');
let message = "Hello " + req.query.name + ". Have a nice day!. Really...";
context.res = {
status: 200,
headers: { 'Content-Type': 'application/json' },
body: {"message": message}
};
context.done();
client.close();
});
});
}
catch(error) {
context.log('caught the error');
context.log(error)
}
};
我在 azure 日志中看到的输出是:
2018-10-26T12:38:07 Welcome, you are now connected to log-streaming service.
2018-10-26T12:38:17.218 [Information] Executing 'Functions.zap-search' (Reason='This function was programmatically called via the host APIs.',
Id=e294fde0-d249-4237-a421-e85bde40f843)
2018-10-26T12:38:17.715 [Information] ******************** 11 *************************
2018-10-26T12:38:18.461 [Information] Executed 'Functions.zap-search' (Succeeded, Id=e294fde0-d249-4237-a421-e85bde40f843)
【问题讨论】:
-
连接mongodb有超时吗?如果
connect通话卡住了一段时间怎么办? -
azure 函数有 5 分钟超时。正如您从日志跟踪中看到的那样,'** 11 **' 日志语句和函数完成之间的时间不到一秒。我也可以通过 robomongo 进行连接,但连接细节相同。根据 mongo 文档,如果未在连接字符串中设置超时,则默认为不超时(docs.mongodb.com/manual/reference/connection-string)。
标签: node.js mongodb azure azure-functions