TypeError: rxjs_1.lastValueFrom is not a function - postgresql

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

Related

[next-auth][error][adapter_error_getUserByAccount]; Cannot read properties of undefined (reading 'findUnique')

I am making a sign up page with 3 providers (Twitter, Facebook and Instagram) using next-auth and prisma with mongoDB. The issue appears when I try to sign up with any of the providers. Here is my nextauth.js file.
import NextAuth from "next-auth"
import { PrismaAdapter } from "#next-auth/prisma-adapter"
import { PrismaClient } from '#prisma/client';
import InstagramProvider from "next-auth/providers/instagram";
import TwitterProvider from "next-auth/providers/twitter";
import FacebookProvider from "next-auth/providers/facebook";
const prisma = new PrismaClient();
export default NextAuth({
adapter: PrismaAdapter(prisma),
providers: [
InstagramProvider({
clientId: process.env.INSTAGRAM_CLIENT_ID,
clientSecret: process.env.INSTAGRAM_CLIENT_SECRET
}),
TwitterProvider({
clientId: process.env.TWITTER_CLIENT_ID,
clientSecret: process.env.TWITTER_CLIENT_SECRET,
version: "2.0",
}),
FacebookProvider({
clientId: process.env.FACEBOOK_CLIENT_ID,
clientSecret: process.env.FACEBOOK_CLIENT_SECRET
}),
],
session: {
strategy: 'jwt',
},
});
I have tried to reinstall all the dependencies, because I don't see what else could be the problem. At first I thought it was the dependencies so I reinstall all the dependencies.
The problem is in your adapter in the [nextauth].js file or wherever you are declaring the prisma instance.
Check out those similar discussions:
https://github.com/nextauthjs/next-auth/discussions/4152
Integrating Prisma Adapter with Next Auth - Unexpected token 'export'
The issue actually comes from the prisma schema. I fixed it after reading the next auth documentation about prisma and mongoDB.

Unale to connect to the postgres from TypeORM

I'm using nestJS to connect to the database with TypeORM as the db package.
My postgres is running in docker with ip 172.17.0.3: 5432
sudo docker run --name postgre -e POSTGRES_USER=admin -e
POSTGRES_PASSWORD=password -p 5432:5432 -v
/data/postgres:/var/lib/postgresql/data -d postgres
Here is my storage module file:
import { Module } from '#nestjs/common';
import { storageConfig, StorageService } from './storage.service';
import { TypeOrmModule} from '#nestjs/typeorm'
import { User } from './entities/user.entity';
#Module({
providers: [StorageService],
imports: [
TypeOrmModule.forRoot({
driver: 'pg',
type: 'postgres',
host: '172.17.0.3',
port: 5432,
username: 'admin',
password: 'password',
database: 'user_storage',
schema: 'public',
entities: [User]
})
]
})
export class StorageModule {}
Now with this I tried importing the users.module.ts
import { Module } from '#nestjs/common';
import { UsersService } from './users.service';
import { UsersController } from './users.controller';
import { TypeOrmModule } from '#nestjs/typeorm'
#Module({
imports: [TypeOrmModule.forRoot()],
controllers: [UsersController],
providers: [UsersService]
})
export class UsersModule {}
and I use repository in a service:
import { Injectable } from '#nestjs/common';
import { UserRequest, UserResponse } from './user.models';
import {DataSource, Repository } from 'typeorm'
import { User } from 'src/storage/entities/user.entity';
#Injectable()
export class UsersService {
private readonly _users: Repository<User>
constructor(private ds: DataSource) {
this._users = this.ds.getRepository(User)
}
async create(req: UserRequest) {
const user = this._users.create()
user.id = 1
user.name = req.name
user.age = req.age
user.address = req.address
user.notes = ''
const saveduser = await this._users.save(user)
return saveduser.id;
}
}
But I keep getting this error whenever I run:
[Nest] 36982 - 07/05/2022, 12:02:19 PM LOG [NestFactory] Starting Nest application...
[Nest] 36982 - 07/05/2022, 12:02:20 PM ERROR [TypeOrmModule] Unable to connect to the database. Retrying (1)... MissingDriverError: Wrong driver: "undefined" given. Supported drivers are: "aurora-mysql", "aurora-postgres", "better-sqlite3", "capacitor", "cockroachdb", "cordova", "expo", "mariadb", "mongodb", "mssql", "mysql", "nativescript", "oracle", "postgres", "react-native", "sap", "sqlite", "sqljs", "spanner".
at DriverFactory.create (/projects/hw/src/driver/DriverFactory.ts:72:23)
at new DataSource (/projects/hw/src/data-source/DataSource.ts:139:43)
at createTypeormDataSource (/projects/hw/node_modules/#nestjs/typeorm/dist/typeorm-core.module.js:172:23)
at Function.<anonymous> (/projects/hw/node_modules/#nestjs/typeorm/dist/typeorm-core.module.js:176:46)
at Generator.next (<anonymous>)
at /projects/hw/node_modules/#nestjs/typeorm/dist/typeorm-core.module.js:20:71
at new Promise (<anonymous>)
at __awaiter (/projects/hw/node_modules/#nestjs/typeorm/dist/typeorm-core.module.js:16:12)
at /projects/hw/node_modules/#nestjs/typeorm/dist/typeorm-core.module.js:174:76
at Observable._subscribe (/projects/hw/node_modules/rxjs/src/internal/observable/defer.ts:55:15) [Nest] 36982 - 07/05/2022, 12:02:20 PM ERROR [TypeOrmModule] Unable to connect to the database. Retrying (1)... TypeError: this.postgres.Pool is not a constructor
at PostgresDriver.createPool (/projects/hw/src/driver/postgres/PostgresDriver.ts:1461:22)
at PostgresDriver.connect (/projects/hw/src/driver/postgres/PostgresDriver.ts:340:38)
at DataSource.initialize (/projects/hw/src/data-source/DataSource.ts:232:27)
at Function.<anonymous> (/projects/hw/node_modules/#nestjs/typeorm/dist/typeorm-core.module.js:179:38)
at Generator.next (<anonymous>)
What is causing this issue and how can I fix it?
For anyone still struggling, another solution for this is to import your ormconfig.js module using commonjs syntax and insert it as the first parameter for TypeORM's forRoot. The reason this happens is because TypeORM does not support TypeScript when applying these settings, so importing your ormconfig.js module using the keyword import won't work, because the correct way of doing that in vanilla NodeJS is using require. Also, don't forget to change your ormconfig.ts -> ormconfig.js:
import { Module } from '#nestjs/common';
import { TypeOrmModule } from '#nestjs/typeorm';
import { AppController } from './app.controller';
import { ConfigModule, ConfigService } from '#nestjs/config';
import { AppService } from './app.service';
import { UsersModule } from './users/users.module';
import { ReportsModule } from './reports/reports.module';
const settings = require('../ormconfig.js');
#Module({
imports: [
ConfigModule.forRoot({
isGlobal: true,
envFilePath: `.env.${process.env.NODE_ENV}`,
}),
TypeOrmModule.forRoot(settings),
UsersModule,
ReportsModule,
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
After much debugging, I was able to find my mistake. in the users.module.ts I had this code:
#Module({
imports: [TypeOrmModule.forRoot()],
controllers: [UsersController],
providers: [UsersService]
})
export class UsersModule {}
I replaced TypeOrmModule.forRoot() with StorageModule and it started working. The problem was that with TypeOrmModule.forRoot() as blank, it wasn't able to utilize any configuration that was provided in StorageModule
The correct one is below:
#Module({
imports: [StorageModule],
controllers: [UsersController],
providers: [UsersService]
})
export class UsersModule {}

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.

ConfigModule isn't working properly in nestjs

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.