0

I'm new to node.js and trying to create a lambda function that queries a collection from MongoDB.

Here is a code I found as a starting point:

'use strict';
const MongoClient = require('mongodb').MongoClient;
const ATLAS_URI = "mongodb://lambdaUser:PASSWORD@cluster0-shard-00-00-ddlwo.mongodb.net:27017,cluster0-shard-00-01-ddlwo.mongodb.net:27017,cluster0-shard-00-02-ddlwo.mongodb.net:27017/mydb?ssl=true&replicaSet=Cluster0-shard-0&authSource=admin";

let cachedDb = null;
function connectToDatabase(uri) {
  console.log('=> connect to database');
  if (cachedDb) {
      console.log('=> using cached database instance');
      return Promise.resolve(cachedDb);
  }

  return MongoClient.connect(uri)
    .then(db => { cachedDb = db; return cachedDb; });
}

function queryDatabase(db) {
  console.log('=> query database');

  return db.collection('sensordata').find({}).toArray()
    .then(() => { return { statusCode: 200, body: 'success' }; })
    .catch(err => { return { statusCode: 500, body: 'error' }; });
}

exports.handler = (event, context, callback) => {
  connectToDatabase(ATLAS_URI)
    .then(db => queryDatabase(db))
    .then(result => {
        console.log('=> returning result: ', result);
        context.succeed(result);
    })
    .catch(err => {
        console.log('=> an error occurred: ', err);
        context.failed(err);
    });
};

This code works fine, but I don't know how to recover the data from the query... Looking other code I see there is a function(err,data) inside the find(), but in this case I don't know how to insert that or modify the code to return the data instead of the {statuscode: 200, body: 'success'} json object.

I would appreciate any help. Thanks Gus

Gus Sabina
  • 189
  • 1
  • 13
  • [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call). And of course the actual documentation examples of [`.find()`](http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#find) should give you a fair indication of usage. It's not like there is a lack of basic examples out there to learn from. – Neil Lunn Aug 27 '17 at 05:39
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – sidgate Aug 28 '17 at 03:56

0 Answers0