Error With Serverless TypeScript With MongoDB + Mongoose On Successive Calls

Hello!

I scaffolded a project with sls create --template aws-nodejs-typescript and then added the “mongoose” npm library to interact with mongo.

I have implemented the GET route localhost:3000/books that returns an object with one property, data, whose value is an array of the books.

I have also implemented a PUT route at localhost:3000/books that inserts an object.

I have implemented the route localhost:3000/books that returns an object with one property, data, whose value is an array of the books.

I tried to extract out the mongo connection stuff and mongoose schema into a helper file:
import * as mongoose from “mongoose”;

let connected = false

export const connectToMongo = async() => {

    if (!connected) {

        console.log('Connecting to mongo...')
        const uri: string = "mongodb://127.0.0.1:27017/local";
        
        await mongoose.connect(uri, (err: any) => {
            if (err) {
                console.log(err.message);
                return err;
            } else {
                console.log("Successfully Connected!");
                connected = true
                return null;
            }
        });
        
    }
}

export interface IBook extends mongoose.Document {
    title: string;
    author: string;
}

export const BookSchema = new mongoose.Schema({
    title: { type: String, required: true },
    author: { type: String, required: true }
});

const Book = mongoose.model<IBook>("Book", BookSchema);
export default Book;

And here’s an example of the “get all books” lambda function handler:
import { APIGatewayProxyHandler } from ‘aws-lambda’;
import ‘source-map-support/register’;
import Book, { connectToMongo } from ‘./utils/mongo-connect’;

export const getAllBooks = async (event, _context, callback) => {
    
    console.log('before connect... ')
    await connectToMongo()
    console.log('after connect... ')

    await Book.find((err: any, books: any) => {

        console.log('got books', books)

        if (err)
            callback({
                statusCode: 400,
                body: JSON.stringify({
                    error: err,
                }, null, 2),
            });
        else
            callback(null, {
                statusCode: 200,
                body: JSON.stringify({
                    data: books,
                }, null, 2)
            });

    });

}

I am getting interesting results when I run it locally with serverless offline start. The first call that I do once I start up the server works great, but any subsequent calls return this error:

Serverless: Warning: handler 'getAllBooks' returned a promise and also uses a callback!

This is problematic and might cause issues in your lambda.
{
“errorMessage”: “Error while loading insertBook”,
“errorType”: “MongooseError”,
“stackTrace”: [
“OverwriteModelError: Cannot overwrite Book model once compiled.”,
“at new OverwriteModelError (/Users/jim/Git-Projects/CRUD-Lambda-TypeScript-Mongo/node_modules/mongoose/lib/error/overwriteModel.js:20:11)”,
“at Mongoose.model (/Users/jim/Git-Projects/CRUD-Lambda-TypeScript-Mongo/node_modules/mongoose/lib/index.js:521:13)”,
“at eval (webpack-internal:///./src/utils/mongo-connect.ts:29:60)”,
“at Module…/src/utils/mongo-connect.ts (/Users/jim/Git-Projects/CRUD-Lambda-TypeScript-Mongo/.webpack/service/src/create.js:109:1)”,
“at webpack_require (/Users/jim/Git-Projects/CRUD-Lambda-TypeScript-Mongo/.webpack/service/src/create.js:20:30)”,
“at eval (webpack-internal:///./src/create.ts:5:78)”,
“at Module…/src/create.ts (/Users/jim/Git-Projects/CRUD-Lambda-TypeScript-Mongo/.webpack/service/src/create.js:97:1)”,
“at webpack_require (/Users/jim/Git-Projects/CRUD-Lambda-TypeScript-Mongo/.webpack/service/src/create.js:20:30)”,
“at /Users/jim/Git-Projects/CRUD-Lambda-TypeScript-Mongo/.webpack/service/src/create.js:84:18”,
“at Object. (/Users/jim/Git-Projects/CRUD-Lambda-TypeScript-Mongo/.webpack/service/src/create.js:87:10)”,
“at Module._compile (internal/modules/cjs/loader.js:955:30)”,
“at Object.Module._extensions…js (internal/modules/cjs/loader.js:991:10)”,
“at Module.load (internal/modules/cjs/loader.js:811:32)”,
“at Function.Module._load (internal/modules/cjs/loader.js:723:14)”,
“at Module.require (internal/modules/cjs/loader.js:848:19)”,
“at require (internal/modules/cjs/helpers.js:74:18)”,
“at Object.createHandler (/Users/jim/Git-Projects/CRUD-Lambda-TypeScript-Mongo/node_modules/serverless-offline/src/functionHelper.js:215:15)”,
“at handler (/Users/jim/Git-Projects/CRUD-Lambda-TypeScript-Mongo/node_modules/serverless-offline/src/ApiGateway.js:485:40)”,
“at module.exports.internals.Manager.execute (/Users/jim/Git-Projects/CRUD-Lambda-TypeScript-Mongo/node_modules/@hapi/hapi/lib/toolkit.js:41:33)”,
“at Object.internals.handler (/Users/jim/Git-Projects/CRUD-Lambda-TypeScript-Mongo/node_modules/@hapi/hapi/lib/handler.js:46:48)”,
“at exports.execute (/Users/jim/Git-Projects/CRUD-Lambda-TypeScript-Mongo/node_modules/@hapi/hapi/lib/handler.js:31:36)”,
“at Request._lifecycle (/Users/jim/Git-Projects/CRUD-Lambda-TypeScript-Mongo/node_modules/@hapi/hapi/lib/request.js:312:68)”,
“at processTicksAndRejections (internal/process/task_queues.js:94:5)”
],
“offlineInfo”: “If you believe this is an issue with serverless-offline please submit it, thanks. https://github.com/dherault/serverless-offline/issues
}

You can find the full project here: https://github.com/JimLynchCodes/CRUD-Lambda-TypeScript-Mongo

Thanks! :pray::heart: