0

I am trying to get the mongodb collection name from an environment variable defined in .env. It looks like the model is initialised before the .env is read.

@model({
  name: 'MyType',
  settings: {
    mongodb: process.env.COLLECTION_NAME,
  },
})

The process.env.COLLECTION_NAME is, at this point, undefined

Any way to externalised the collection name? Many thanks for the help.

Mustaq
  • 35
  • 1
  • 5

2 Answers2

0

By default, Node.js does not read from .env.

To read from .env, we need to utilize the dotenv package.

Since models are resolved through the Booter during startup, hence we need to call dotenv.config() before app.boot().

Update index.ts as follows:

// At the top of the file
import dotenv from 'dotenv';

...

// Inside the main function
// dotenv.config() must appear before app.boot()

dotenv.config()
...
app.boot();
app.start();

This would cause dotenv to overwrite process.env with the values in .env where necessary.

Further reading:

Rifa Achrinza
  • 1,555
  • 9
  • 19
  • `Thanks Rifa.` `Using dotenv, ok elsewhere in the project. ` `The problem is with the model. Looks like this is executed before the .env is read.` `The example code here:` `const mongodbCollection = {` `collection: process.env.COLLECTION_NAME ?? 'my_collection',` `};` console.log(process.env.COLLECTION_NAME); and I am getting on the console: undefined Server is running at http://127.0.0.1:8080/dev/project/v1 Try http://127.0.0.1:8080/dev/project/v1/ping This (undefined) shows the model is initialised before the .env read` – Mustaq Aug 30 '20 at 10:38
  • Thanks again. Tried, still getting "undefined" – Mustaq Aug 30 '20 at 11:21
0

in your

src/index.ts

import {ApplicationConfig, MyApplication} from './application';
require('dotenv').config();
export * from './application';

and your .env file in the "root" of your project