12

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>;

4 Answers 4

15

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

9

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

5
  • I don't think I'm using higher version. These are mongoose dependencies from pck.json. "dependencies": "mongoose": "^5.9.23", "@nestjs/mongoose": "^7.0.2", "devDependencies": "@types/mongoose": "^5.7.31",
    – Seeschon
    Dec 2, 2020 at 8:38
  • You can check the version by running npm ls --depth=0 | grep mongoose or yarn list --depth=0 | grep mongoose. Using ^5.9.23 means it will use 5.x.x so long as it is above 5.9, because the ^ means this version or minor version above Dec 2, 2020 at 16:18
  • Tks, still getting: MongooseModule] Unable to connect to the database. Retrying (3)... +3006ms, although I downgraded to 5.10.2. any help further ?
    – Seeschon
    Dec 2, 2020 at 22:34
  • You can let it count to nine (9) and it will print out the problem. Looking at your config, it looks like you may be missing the ? for the query parameters. Dec 2, 2020 at 22:38
  • 2
    To prevent updating Mongoose to > 5.11.x you can change in package.json` "mongoose": "^5.10.x" to "mongoose": "~5.10.x".
    – guizo
    Dec 6, 2020 at 19:57
4

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 ...

2

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.

2
  • after update package.json what did you do next ? make any command related to yarn / npm update or something ? because index.d.ts can't be created itself, at least not in my case
    – Seeschon
    Dec 3, 2020 at 15:00
  • @TheKash I installed dependecies again. ran command npm install after removing node_modules and package-lock Dec 4, 2020 at 9:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.