Using process env inside mongoose Schema file Nestjs

Viewed 37

I need to change the default value of one property in Mongoose Schema based on one environment variable, but when I try to access process.env.NAME I get undefined instead of the value inside my .env file. I have this in my schema

import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document } from 'mongoose';

export type PetDocument = Pet & Document;

@Schema()
export class Pet {
  @Prop({ default: process.env.NAME })
  name: string;

  @Prop()
  age: number;

  @Prop()
  breed: string;
}

export const PetSchema = SchemaFactory.createForClass(Pet);

And this is my Pet Module

import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { MongooseModule } from '@nestjs/mongoose';
import { PetsService } from './pets.service';
import { Pet, PetSchema } from './schema/pets.schema';

@Module({
  imports: [
    ConfigModule,
    MongooseModule.forFeatureAsync([
      {
        name: Pet.name,
        useFactory: () => PetSchema,
      },
    ]),
  ],
  providers: [PetsService],
})
export class PetsModule {}

and this is my App Module

import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { MongooseModule } from '@nestjs/mongoose';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { PetsModule } from './pets/pets.module';

@Module({
  imports: [
    ConfigModule.forRoot({
      isGlobal: true,
    }),
    MongooseModule.forRootAsync({
      useFactory: () => ({
        uri: process.env.DB_URI,
      }),
    }),
    PetsModule,
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

How can I get the value instead of undefined inside my Schema file?

1 Answers

You need include dotenv package to read the .env file at the top of the Schema file. First install the dotenv package if you haven't done this yet: npm i dotenv

require('dotenv').config();
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document } from 'mongoose';

export type PetDocument = Pet & Document;

@Schema()
export class Pet {
  @Prop({ default: process.env.NAME }) // shouldn't be undefined anymore

.......
Related