简体   繁体   中英

how to establish the connection between nodejs and mongodb on aws lambda?

I am using MongoDB database and Aws lambda function in my project. When i tried access Mongodb dataabse through Aws lambda node js function, i get some error. find the below code

var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://username:password@localhost:27017/";

MongoClient.connect(url, function(err, db) {
if (err) throw err;
});

I get some error like this below:

Response:
{
"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/index.js:1:81)",
"Module._compile (module.js:652:30)",
"Object.Module._extensions..js (module.js:663:10)",
"Module.load (module.js:565:32)",
"tryModuleLoad (module.js:505:12)",
"Function.Module._load (module.js:497:3)"

] }

How to connect mongdb and aws lambda function through node.js???

I think you forgot to npm install the module. Try

npm install mongodb

You have a few problems here you need to address:

  • You need to install mongodb as fly mentioned above. I am not sure how you are deploying to AWS Lambda, but you usually install it locally, adding it to your package.json file. Then once you deploy, AWS reads that file and installs it on your Lambda instance.

  • Your Lambda instance will not be able to reach your localhost database instance because it is local to your computer only. You can set one up here at https://www.mongodb.com/cloud/atlas and then use that database URL to connect from your AWS Lambda instance.

  • If you are working on your localhost, your database url should be "mongodb://localhost:27017/"; . You only include the username:password portion when you are in fact using them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM