1

I'm creating a connection for my MongoDB Atlas using NodeJS in a AWS Lambda function. I was able to make a successful connection, but when I do the .find({}) to get all data I get an empty array.

Lambda

const mongoose = require('mongoose');

let conn = null;

const uri = 'mongodb+srv://xxx:[email protected]/test';
let M = null;
exports.handler = async function(event, context) {
  nodejs-aws-lambda-mongodb-atlas
  context.callbackWaitsForEmptyEventLoop = false;
  if (conn == null) {
    conn = await mongoose.createConnection(uri, {
      bufferCommands: false,
      bufferMaxEntries: 0,
      useNewUrlParser: true
    });
    M = conn.model('Todo', new mongoose.Schema(
      {
        title: String,
        description: String,
        date: Date,
        status: String
      }
    ));
  }


  const doc =  M.find({});
  console.log('items in the DB')
  console.log(doc);

  return null;
}; 

Documentation Mongoose AWS Lambda: https://mongoosejs.com/docs/lambda.html

UPDATE:

 M.find({}).exec().then(function(allDocs){
    console.log('getting al docs')
    console.log(allDocs)//[]
  });

MongoDB Atlas

enter image description here

1
  • Should have been mongoose.model instead of conn.model Commented Jun 6, 2019 at 18:06

1 Answer 1

1

find is async so I think you need to do:

M.find({}).exec().then(function(allDocs){
   //do your thing
});

or await it

let alldocs = await M.find({});
Sign up to request clarification or add additional context in comments.

2 Comments

Hi! Thanks for the help. I didn't work tho. I have updated my question
What happens when you use await M.find({})?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.