0

I want to boot a memory mongodb for my local development with serverless

This is the plugin I did

const { MongoMemoryServer } = require('mongodb-memory-server')

class MongoMemoryServerPlugin {

    constructor(){
        this.mongod

        this.hooks = {
            'before:offline:start:init': () => this.init(),
            'before:offline:start:end': () => this.end(),
        }

    }

    async init() {
        console.log('Starting Mongodb Memroy Server');
        this.mongod = await MongoMemoryServer.create();
        process.env.MONGODB_URI = this.mongod.getUri();
    }

    async end() {
        console.log('Stopping Mongodb Memroy Server');
        if(this.mongod) this.mongod.stop()
    }
}

module.exports = MongoMemoryServerPlugin

And in my serverless.yml I have

plugins:
  - serverless-offline
  - ./plugin/mongodbMemoryServer.js

I have the log when starting and when ending but process.env.MONGODB_URI is not accessible from the serverless code

const mongodb = require("mongodb");

let cachedDb = null;

module.exports.connect = async function connect() {
    if (cachedDb) return cachedDb;

    if (!process.env.MONGODB_URI) throw new Error('Environment variable MONGODB_URI not defined')

    const client = await mongodb.MongoClient.connect(process.env.MONGODB_URI);

    const db = client.db("db");

    cachedDb = db;
    return db;
}

when trying to connect, I have Environment variable MONGODB_URI not defined

1 Answer 1

0

You will need to provide that environment variable to the lambda you are deploying.

in serverless.yml, you can set it up in the following way in your lambda definition:

functions:
  my_function:
    handler: *****
    environment:
      MONGODB_URI: *your_uri*
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.