I am using latest version (current date is 04/05/2023) and solved this issue. Some of this step is optional but good to try!
Open terminal and make sure MongoDB is running net start MongoDB
Make sure your connection is success by test connection in MongoDB Compass
note: this code below will generate database (or just make new collection, if the db is already exist) automatically in your mongoDB.
Nest Js code
app.module.ts
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { MongooseModule } from '@nestjs/mongoose';
import { CatModule } from './cat/cat.module';
@Module({
imports: [
MongooseModule.forRoot('mongodb://127.0.0.1:27017/nest', {
useNewUrlParser: true, useUnifiedTopology: true
}),
CatModule,
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule { }
cat.module.ts
import { Module } from '@nestjs/common';
import { CatController } from './cat.controller';
import { CatService } from './cat.service';
import { MongooseModule } from '@nestjs/mongoose';
import { Cat, CatSchema } from './cat.model';
@Module({
imports: [
MongooseModule.forFeature([
{ name: Cat.name, schema: CatSchema },
])
],
controllers: [CatController],
providers: [CatService]
})
export class CatModule { }
cat.service.ts
import { Injectable } from '@nestjs/common';
import { InjectConnection, InjectModel } from '@nestjs/mongoose';
import { Cat, CatDocument } from './cat.model';
import { Connection, Model } from 'mongoose';
import { CreateCatDto } from './dto/create-cat.dto';
@Injectable()
export class CatService {
constructor(
@InjectModel(Cat.name) private catModel: Model<CatDocument>) { }
}
cat.model.ts
import { Prop, Schema, SchemaFactory } from "@nestjs/mongoose";
import { Document } from 'mongoose';
export type CatDocument = Cat & Document;
@Schema()
export class Cat {
@Prop()
id: number;
@Prop()
name: string;
@Prop()
health: string;
}
export const CatSchema = SchemaFactory.createForClass(Cat);
MongooseModule.forRootAsync({ useFactory: () => ({ uri: 'mongodb://localhost:27017/snaptoon', }), }),
– ShelleyuseCreateIndex:true
and it connected. – Algid