AWS Lambda can not insert data into mongo

223 views
Skip to first unread message

Miqayel Sargsyan

unread,
Aug 6, 2018, 5:01:11 PM8/6/18
to mongodb-user

I have nodejs app working on lambda. I need to insert data into mongo but lambda can not do it or even don't connect.

Here is my code:


MongoClient.connect(dbURL, {useNewUrlParser: true }, function (err, db){

         
if (err) {
            console
.log('Unable to connect to the mongoDB server. Error: ', err);
         
} else {
            console
.log('Connection established to ', dbURL);
         
}
          let myDB
= db.db('iyc')

        let arr
= [];

          locations
.forEach(element => {
            let insertData
= {};
            insertData
.user_id = req.body.user_id;
            insertData
.device_id = req.body.device_id;
            insertData
.app_type = req.body.app_type;
            insertData
.datetime = JSON.parse(element.datetime)/1000;
            insertData
.latitude = element.latitude;
            insertData
.longitude = element.longitude;
            insertData
.address = element.address;
            insertData
.method = element.method;
            insertData
.accuracy = element.accuracy;
            insertData
.status = element.status;
            insertData
.confidence = element.confidence
           arr
.push(insertData)
         
})

         
try {
            myDB
.collection('userdevices').insertMany(arr, function(err, data) {
             
if(err) {
                console
.log("Insert db err " + err)
             
} else if(!data) {
                console
.log('No data has been inserted')
             
}

           
})
           
}
         
catch(err) {
            console
.log(err)
         
}
          db
.close();


Kevin Adistambha

unread,
Aug 27, 2018, 2:05:02 AM8/27/18
to mongodb-user

Hi Miqayel,

I need to insert data into mongo but lambda can not do it or even don’t connect.

If you’re still having this issue, could you please double-check that Lambda is allowed to access your MongoDB instance (assuming you deployed your own instance). Particularly, whitelisting, firewall rules, and mongod bindIp setting which was changed in MongoDB 3.6 to bind to localhost by default. Without a change in this setting, a MongoDB deployment is only accessible from the host itself.

With regards to Lambda functions, you might want to have a look at the blog post Optimizing AWS Lambda performance with MongoDB Atlas and Node.js, which contains tips to optimize Lambda connection to MongoDB.

Best regards,
Kevin

Reply all
Reply to author
Forward
0 new messages