"db is not defined" error when trying to connect to MySQL database

Issue

I am trying to build an AWS Lambda function with Node.JS. This is my code. I am super new to Node.JS.

var response;

var mysql = require('mysql');
var con = mysql.createConnection({
    host: "*****.rds.amazonaws.com",
    user: "****",
    password: "***",
    database: "***",
    port: 3306
}); 
    

exports.lambdaHandler = async (event, context) => {

    con.connect();

    try{
        db.query( 'SELECT * from accounting_type' ).then( rows => {
            response = {
                'statusCode': 200,
                'body': JSON.stringify({
                    rows,
                })
            }
          } );
    }
    catch(err)
    {
        console.log(err);
        response = {
            'statusCode': 200,
            'body': JSON.stringify({
                err,
            })
        }
    }
    return response;

};

template.yaml

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: >
  node2

  Sample SAM Template for node2
  
# More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst
Globals:
  Function:
    Timeout: 3

Resources:
  HelloWorldFunction:
    Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
    Properties:
      CodeUri: hello-world/
      Handler: app.lambdaHandler
      Runtime: nodejs14.x
      Events:
        HelloWorld:
          Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api
          Properties:
            Path: /hello
            Method: get
      Role: !GetAtt LambdaRole.Arn
      VpcConfig:
        SecurityGroupIds:
          - sg-041f2459dcd921e8e
        SubnetIds:
          - subnet-0456db2d
          - subnet-c6414cb
 
  LambdaRole:
    Type: 'AWS::IAM::Role'
    Properties:
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Effect: Allow
            Principal:
              Service:
                - lambda.amazonaws.com
            Action:
              - 'sts:AssumeRole'
      Path: /
      ManagedPolicyArns:
        - arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
      Policies:
        - PolicyName: root
          PolicyDocument:
            Version: "2012-10-17"
            Statement:
              - Effect: Allow
                Action:
                  - ec2:DescribeNetworkInterfaces
                  - ec2:CreateNetworkInterface
                  - ec2:DeleteNetworkInterface
                  - ec2:DescribeInstances
                  - ec2:AttachNetworkInterface
                Resource: '*'

When executed, the code returns me the below error

START RequestId: 026dc152-40d0-49d3-b764-ded5f0cbc2b7 Version: $LATEST
2021-07-20T08:01:48.401Z    026dc152-40d0-49d3-b764-ded5f0cbc2b7    INFO    ReferenceError: db is not defined
    at Runtime.exports.lambdaHandler [as handler] (/var/task/app.js:20:9)
    at Runtime.handleOnce (/var/runtime/Runtime.js:66:25)
END RequestId: 026dc152-40d0-49d3-b764-ded5f0cbc2b7
REPORT RequestId: 026dc152-40d0-49d3-b764-ded5f0cbc2b7  Duration: 1609.64 ms    Billed Duration: 1610 ms    Memory Size: 128 MB Max Memory Used: 80 MB  Init Duration: 152.15 ms    
XRAY TraceId: 1-60f682ea-66ea5e370df8860b12cf43fd   SegmentId: 5d2fad42374469c0 Sampled: true

Solution

You are assigning the mysql connection cursor to con variable and using db in your query, hence db is undefined. Replace db with con like this:

con.query( 'SELECT * from accounting_type' , (err,rows) => {
            if(err){
               console.error(err)
               return
            }
            response = {
                'statusCode': 200,
                'body': JSON.stringify({
                    rows,
                })
            }
          });

Updated the answer to use the (err,rows) callback instead of .then , since .then is not available as per the docs.

Answered By – Ankit Gupta

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published