Seeschon
Seeschon

Reputation: 448

Errors while initializing MongoDB with Nestjs/Angular

I finally came here after putting lot of efforts but no success. I learn Nestjs/Angular/MongoDB. So far I got success running both Angular server & Nestjs server simaltaneously. But I get huge list of errors 147 (mostly related to schema) when I initialize mongoDB with them.

It doesn't seem that errors are related to my codes, but install dependencies. In any case I copy hereunder my codes as well. I try this app both ubuntu & windows. but same error persist.

app.controller.ts:

import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';

@Controller()
 export class AppController {
 constructor(private readonly appService: AppService) {}

@Get()
 healthCheck(): string {
  return this.appService.appStatus();
  }
}

App.module.ts

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

@Module({
  imports: [
    MongooseModule.forRoot(config.mongoUri, {
      useNewUrlParser: true,
      useUnifiedTopology: true,
      useCreateIndex: true,
    }),
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

app.service.ts

import { Injectable } from '@nestjs/common';
import { InjectConnection } from '@nestjs/mongoose';
import { Connection } from 'mongoose';
import { config } from './config';

@Injectable()
export class AppService {
  constructor(@InjectConnection() private connection: Connection) {}
   appStatus(): string {
   return `${config.appName} is running in port ${config.port}. Connected to 
    ${this.connection.name}`;
  }
}

config.ts

import * as dotenv from 'dotenv';

const result = dotenv.config();

 if (result?.error) {
 throw new Error('Add .env file');
}

export const config = {
  env: process.env.SZ_ENV,
  appName: process.env.SZ_APP,
  port: process.env.SZ_PORT,
  mongoUri:  
 `mongodb+srv://${process.env.SZ_MONGO_USER}:${process.env.SZ_MONGO_PASS}@
  ${process.env.SZ_MONGO_HOST}/${process.env.SZ_MONGO_DB} 
  authSource=admin&replicaSet=${process.env.SZ_MONGO_REPLICA}&
  readPreference=primary&ssl=true`,
  };

main.ts

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { config } from './config';

 async function bootstrap() {
  const { appName, port } = config;
  const app = await NestFactory.create(AppModule);
  await app.listen(port, () => {
    console.info(`${appName} is running in http://localhost:${port}`);
  });
 }
bootstrap();

ERROR: while yarn start:server

[8:16:58 PM] Starting compilation in watch mode...

node_modules/@nestjs/mongoose/dist/factories/schema.factory.d.ts:4:60 - error TS2315: Type 
'Schema' is not generic.

4     static createForClass<T = any>(target: Type<unknown>): mongoose.Schema<T>;
                                                         ~~~~~~~~~~~~~~~~~~
node_modules/@types/mongoose/index.d.ts:79:1 - error TS6200: Definitions of the following 
identifiers conflict with those in another file: DocumentDefinition, FilterQuery, 
UpdateQuery, NativeError, Mongoose, CastError, Collection, Connection, Error, QueryCursor, 
VirtualType, Schema, Subdocument, Array, DocumentArray, Buffer, ObjectId, Decimal128, Map, 
Aggregate, SchemaType, Document

79     declare module "mongoose" {

 node_modules/mongoose/index.d.ts:1:1
 1 declare module "mongoose" {
   ~~~~~~~
 Conflicts are in this file.

 node_modules/@types/mongoose/index.d.ts:226:14 - error TS2403: Subsequent variable 
 declarations must have the same type.  Variable 'SchemaTypes' must be of type 'typeof 
 Types', but here has type 'typeof Types'.

 226   export var SchemaTypes: typeof Schema.Types;
              ~~~~~~~~~~~

 node_modules/mongoose/index.d.ts:45:14
 45   export var SchemaTypes: typeof Schema.Types;
                 ~~~~~~~~~~~
 'SchemaTypes' was also declared here.

 node_modules/@types/mongoose/index.d.ts:822:24 - error TS2314: Generic type 
 'Query<ResultType, DocType, T>' requires 3 type argument(s).

 822     constructor(query: Query<T>, options: any);
                        ~~~~~~~~

 node_modules/@types/mongoose/index.d.ts:1013:19 - error TS2314: Generic type 
 'Query<ResultType, DocType, T>' requires 3 type argument(s).

 1013     pre<T extends Query<any> = Query<any>>(
                    ~~~~~~~~~~

 node_modules/@types/mongoose/index.d.ts:1013:32 - error TS2314: Generic type 
 'Query<ResultType, DocType, T>' requires 3 type argument(s).

 1013     pre<T extends Query<any> = Query<any>>(
                                 ~~~~~~~~~~

 node_modules/@types/mongoose/index.d.ts:1036:48 - error TS2314: Generic type 
 'Query<ResultType, DocType, T>' requires 3 type argument(s).

 1036     pre<T extends Document | Model<Document> | Query<any> | Aggregate<any>>(
                                                 ~~~~~~~~~~

 node_modules/@types/mongoose/index.d.ts:1048:19 - error TS2314: Generic type 
 'Query<ResultType, DocType, T>' requires 3 type argument(s).

 1048     pre<T extends Query<any> = Query<any>>(
                    ~~~~~~~~~~

 node_modules/@types/mongoose/index.d.ts:1048:32 - error TS2314: Generic type 
 'Query<ResultType, DocType, T>' requires 3 type argument(s).

 1048     pre<T extends Query<any> = Query<any>>(
                                 ~~~~~~~~~~

 node_modules/@types/mongoose/index.d.ts:1074:48 - error TS2314: Generic type 
 'Query<ResultType, DocType, T>' requires 3 type argument(s).

 1074     pre<T extends Document | Model<Document> | Query<any> | Aggregate<any>>(
                                                 ~~~~~~~~~~

 node_modules/@types/mongoose/index.d.ts:1264:5 - error TS2374: Duplicate string index 
 signature.

 1264     [path: string]: SchemaTypeOpts<any> | Schema | SchemaType;
      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

 node_modules/@types/mongoose/index.d.ts:1627:76 - error TS2314: Generic type 
'Query<ResultType, 
   DocType, T>' requires 3 type argument(s).

 1627     replaceOne(replacement: any, callback?: (err: any, raw: any) => void): Query<any>;

Upvotes: 12

Views: 6349

Answers (4)

Anatoly
Anatoly

Reputation: 5243

New mongoose v5.11.x released its own types definition, so you shouldn't use @types/mongoose anymore https://github.com/Automattic/mongoose/issues/9606#issuecomment-736710621

Upvotes: 15

mazdak
mazdak

Reputation: 185

I had this bug too , and change dependencies (mongoose) didn't work. just add this to compilerOptions in tsconfig.json

"skipLibCheck": true

maybe it is bad practice but ...

Upvotes: 4

Vikas Chauhan
Vikas Chauhan

Reputation: 1474

I was also facing the same issue so I found that it is due to the mongoose version "version": "5.11.2" as I described the mongoose version "mongoose": "^5.10.11" in package.json. There was an index.d.ts file was created while facing this issue. I changed it to "mongoose": "~5.10.11" and it installed the "version": "5.10.19" It worked.

Do not know what is the issue with the latest version they might have released it with a bug left.

Upvotes: 2

Jay McDoniel
Jay McDoniel

Reputation: 70131

This is most likely related to Mongoose v5.11.0 which added its own types. Reverting to v5.10.x should fix it

Upvotes: 9

Related Questions