ConfigModule isn't working properly in nestjs - mongodb

I am working on nestjs and mongoose recently. I put my MongoDB connection links on .env file. I have configured my nestjs application using ConfigModule. I followed the nestjs docs. But I have no idea why env variables are not working for me.
I have one extra module.ts file called content.module.ts in which I am connecting to mongodb. I have configured this ConfigModule in my app.module.ts and put it as global.
// app.module.ts
#Module({
imports: [
ConfigModule.forRoot({
envFilePath: './config/.env',
isGlobal: true,
}),
ContentModule, //another module
],
})
export class AppModule {}
// content.module.ts
#Module({
imports: [
MongooseModule.forRoot(process.env.CONTENT_DB_CONNECTION_STRING),
MongooseModule.forFeature([{ name: 'App', schema: AppSchema },]),
],
})
export class ContentModule {}
When I run my project using the debugger, I found that MongooseModule was first getting executed in the content.module.ts file, and then configModule was getting executed.
I even tried to configure the configModule in the content.module.ts file itself like below but no luck.
#Module({
imports: [
ConfigModule.forRoot({
envFilePath: '../../config/.env',
}),
MongooseModule.forRoot(process.env.CONTENT_DB_CONNECTION_STRING),
MongooseModule.forFeature([{ name: 'App', schema: AppSchema },]),
],
})
export class ContentModule {}
.env file
PORT=3000
CONTENT_DB_CONNECTION_STRING=mongodb://localhost:27017/content
project structure
I didn't get why mongoose dependencies are getting executed before the nestjs dependencies? And I also need help to fix this env variable.

Related

Mongo doesn't let NestJS create a new DB

I have a backend with NestJS, it is configured with mongoose. The app.module.ts :
#Module({
imports: [
MongooseModule.forRoot('mongodb://admin:root#localhost:27017/'),
CatsModule
],
controllers: [],
providers: [],
})
If I let the URI like this it works correctly but creates a 'tests' database. I want a custom database, so when I try to set the URI to mongodb://admin:root#localhost:27017/my-custom-db it cant connect...
I've tried to create my-custom-db manually, but it still fails
The error :
[Nest] 14480 - 26/06/2022, 12:28:27 ERROR [MongooseModule] Unable to connect to the database. Retrying (1)...
The Problem was because Mongoose use a diferent format to connect to a specific database, we have to pass the name by option:
#Module({
imports: [
MongooseModule.forRoot(
'mongodb://localhost:27017',
{useNewUrlParser:true,user:"root",pass:"example",dbName:"nest"}),
UserModule],
controllers: [AppController],
providers: [AppService],
})

typeORM postgres don't seem to find database

I'm using windows 10, Nest.js and typeORM.
Previously, I had to create a new user\role uder my windows user - but now the ORM don't seem to find my db (called steamClone) - and calls a db named after my user:
error: database "Itay" does not exist
typeORM is configured like such encapsulated in a module:
import { Module } from '#nestjs/common';
import { TypeOrmModule } from '#nestjs/typeorm';
import {ConfigModule, ConfigService} from '#nestjs/config';
#Module({
imports: [
TypeOrmModule.forRootAsync({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: (ConfigService: ConfigService) => ({
type: 'postgres',
host: ConfigService.get('DB_HOST'),
port: ConfigService.get('DB_PORT'),
username: ConfigService.get('DB_USER'),
password: ConfigService.get('DB_PASSWORD'),
database: ConfigService.get('DB_DATABASE'),
entities: [__dirname + '/../**/*.entity{.ts,.js}'],
synchronize: true,
})
})
],
})
export class DatabaseModule {}
all of the parameters are stored in a .env file
running on localhost, default port and everything, postgres user etc.
would love to know how to solve this

Mongoose Error: Cannot read property 'length' of undefined in NestJs

I am using nests framework and versions of mongodb and mongoose are as specified below.
Please refer to the screenshot for error in detail.
versions
"mongodb": "4.0.0",
"mongoose": "5.5.12",
Error Screenshot
User Document Module
import { Module } from '#nestjs/common';
import { UserDocumentsService } from './user-documents.service';
import { UserDocumentsController } from './user-documents.controller';
import { MongooseModule } from '#nestjs/mongoose';
import { UserDocumentsSchema } from './schema/user-documents.schema';
#Module({
imports: [
// showing error on this line
MongooseModule.forFeature([
{ name: 'UserDocument', schema: UserDocumentsSchema },
]),
],
controllers: [UserDocumentsController],
providers: [UserDocumentsService],
})
export class UserDocumentsModule {}
App.module.ts
#Module({
imports: [
MongooseModule.forRootAsync({
imports: [SharedModule],
useFactory: async (configService: ConfigService) => ({
uri: configService.mongoDBName(),
useNewUrlParser: true,
useFindAndModify: false,
}),
inject: [ConfigService],
}),
UserDocumentsModule,
],
providers: [AppGateway],
})
export class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer): MiddlewareConsumer | void {
consumer.apply(contextMiddleware).forRoutes('*');
}
}
UPDATE
I think there is something wrong with the mongoose imports in the schema file. It says "could not find declaration for module 'mongoose'".
I tried removing and reinstalling mongoose and it's types. But now it shows new error.
I tried solutions mentioned in this post:
Node.js heap out of memory
But this also didn't work for me.
I'm using Mac-M1 with 8GB config.
UPDATE
The issue has been resolved now. The project is running on node v10.24.1 and I was using node v16.6.2.
After downgrading node version using NVM, this issue is gone.
You'll have to pull SharedModule import off MongooseModule.
Try this:
#Module({
imports: [
MongooseModule.forRootAsync({
useFactory: async (configService: ConfigService) => ({
uri: configService.mongoDBName(),
useNewUrlParser: true,
useFindAndModify: false,
}),
inject: [ConfigService],
}),
UserDocumentsModule,
SharedModule
],
providers: [AppGateway],
})
export class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer): MiddlewareConsumer | void {
consumer.apply(contextMiddleware).forRoutes('*');
}
}
It was because I was using a wrong version of node. The project was built on node v10.24.1 and I was using node v16.6.2.
After downgrading node version using NVM, I was able to fix this issue.

TypeError: rxjs_1.lastValueFrom is not a function

I am building an api using nestjs. After adding the typeorm and pg dependencies and adding the TypeOrmModule.forRoot({}) code in app.module.ts like shown below.
import { Module } from '#nestjs/common';
import { TypeOrmModule } from '#nestjs/typeorm';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { CoffeesModule } from './coffees/coffees.module';
#Module({
imports: [CoffeesModule, TypeOrmModule.forRoot({
type: 'postgres',
host: 'localhost',
port: 5432,
username: 'postgres',
password: 'xxx',
database: 'postgres',
autoLoadEntities: true,
synchronize: true
})],
controllers: [AppController],
providers: [AppService],
})
export class AppModule { }
I get an error TypeError: rxjs_1.lastValueFrom is not a function with but no error when I exclude TypeOrmModule.forRoot({}).
What could be the reason for the error ?
If you're using Nest v8, RxJS version 7 is used, which no longer has a toPromise() method for Observables, so Nest uses the lastValueFrom method instead. If you're receiving this error, you probably need to update your rxjs dependency to >7.
npm i rxjs#^7
yarn add rxjs#^7
pnpm i rxjs #^7
Pick your flavor of package manager and have at it.
In the last update of NestJS, when is used cli to initialization of project this error is throw.
The real answer
The issue is conflict with nest version.. anyone who see this - just make sure all your nestJs packages are of version 7 or 8 - don't mix them. especially those:
#nestjs/common
#nestjs/core
#nestjs/typeorm
from here: https://github.com/nestjs/nest/issues/7468#issuecomment-876174870
update "#nestjs/typeorm": "^7.1.5" in package.json and enter npm i and restart server

How to connect mongo with nestJs?

If I config mongo with nest js its come like this,
my files like this,
app.module.ts
item.schema.ts
items.module.ts
items.service.ts
I use a forwardRef in the other modules where I declare the mongo models like this:
#Module({
imports: [
forwardRef(() => AppModule),
MongooseModule.forFeature([{ name: 'User', schema: UserSchema }])
]
})
Where AppModule my app.module is
Just remove the ItemsService from the AppModule and exports it on your ItemsModule, besides no need to define the ItemsController on the AppModule it's enough to be defined on the ItemsModule.
You may have a look about contollers and exports following this link https://docs.nestjs.com/modules