Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AWS Lambda error "Cannot find module 'mongodb'"

I've successfully deployed my function to AWS.

When trying to invoke the function (serverless invoke -f facebookAdInsert -l), I get the following error:

{
    "errorMessage": "Cannot find module 'mongodb'",
    "errorType": "Error",
    "stackTrace": [
        "Function.Module._load (module.js:474:25)",
        "Module.require (module.js:596:17)",
        "require (internal/module.js:11:18)",
        "Object.<anonymous> (/var/task/src/facebookAdInsert.js:222:18)",
        "__webpack_require__ (/var/task/src/facebookAdInsert.js:20:30)",
        "Object.<anonymous> (/var/task/src/facebookAdInsert.js:234:16)",
        "__webpack_require__ (/var/task/src/facebookAdInsert.js:20:30)",
        "Object.<anonymous> (/var/task/src/facebookAdInsert.js:303:16)",
        "__webpack_require__ (/var/task/src/facebookAdInsert.js:20:30)"
    ]
}

Here are my dependencies:

"dependencies": {
    "@babel/core": "^7.3.4",
    "@babel/preset-env": "^7.3.4",
    "aws-sdk": "^2.268.1",
    "babel-loader": "^8.0.5",
    "babel-plugin-transform-runtime": "^6.23.0",
    "babel-preset-env": "^1.7.0",
    "babel-preset-es2015": "^6.24.1",
    "dotenv": "^6.0.0",
    "moment": "^2.24.0",
    "mongodb": "^3.1.10",
    "mongoose": "^5.4.17",
    "parse-mongo-url": "^1.1.1",
    "request": "^2.88.0",
    "serverless-offline": "^3.33.0",
    "serverless-webpack": "^5.2.0",
    "webpack": "^4.29.6",
    "webpack-node-externals": "^1.7.2"
}

Any ideas as to what the issue could be? Based on my research possible solutions were running npm install before deploying and moving all "devDependencies" to "dependencies" but those have not worked.

like image 227
anti_circle Avatar asked Oct 24 '25 10:10

anti_circle


1 Answers

You are missing the mongodb layer for AWS lambda

Open a terminal and type

  1. mkdir nodejs
  2. cd nodejs
  3. npm init -y
  4. npm install mongodb
  5. zip the entire nodejs folder, making sure that if you unzip the folder you get the following structure
    nodejs
      +---node_modules
             +---------- (mongodb and other folders)
  1. Upload this layer to AWS Lambda
  2. Add the layer to your Lambda function

With this it should work without problems.

Regards

like image 179
Leonel Corso Avatar answered Oct 26 '25 01:10

Leonel Corso