azure function (node) calling mongodb finishes wit

2019-03-03 13:55发布

问题:

I have a node function that calls mongo to request some data. There is no error but it does not seem to connect to mongo and get the data either. Is there something I'm not doing right?

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)
    }
};

The output I see in azure logs is:

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)

回答1:

When using V2 of Azure functions you need to decide if you are going to be using promises or callbacks. The code you posted is callback based but exported as a promise because of the use async keyword and since the MongoClient.connect is not awaited the runtime exits your function before executing these results. If you remove the async keyword should start seeing the desired results.