Skip to content

Instantly share code, notes, and snippets.

@cherryramatisdev
Created November 30, 2022 16:13
Show Gist options
  • Save cherryramatisdev/3453f44b96d0945810a45f05fee66c51 to your computer and use it in GitHub Desktop.
Save cherryramatisdev/3453f44b96d0945810a45f05fee66c51 to your computer and use it in GitHub Desktop.
How to setup mongoDB using typeorm on nestjs
import { Module, NestModule } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
@Module({
imports: [
TypeOrmModule.forRoot({
...{
type: 'mongodb',
url: '<your-mongo-db-atlas-url-here>',
synchronize: false,
logging: false,
entities: [__dirname + '../../teste/entities/*.entity{.ts,.js}'], // Insert the path for your entities
},
name: 'mongo', // name the connection to handle multiple databases
}),
],
providers: [],
})
export class DefaultModule implements NestModule {}
import { Controller, Get } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { MongoRepository } from 'typeorm';
import { TestEntity } from './entities/test.entity';
@Controller('test')
export class TestController {
constructor(
@InjectRepository(TestEntity, 'mongo')
private readonly repository: MongoRepository<TestEntity>,
) {}
// This method is performing an atlas search (https://www.mongodb.com/atlas/search) as an example
@Get()
public testMethod() {
return this.repository.aggregate([
{
$search: {
index: 'default',
text: {
query: 'per inf',
path: {
wildcard: '*',
},
},
},
},
]).toArray()
}
}
import { Column, Entity, ObjectID, ObjectIdColumn } from 'typeorm';
@Entity('test')
export class TestEntity {
@ObjectIdColumn()
id: ObjectID;
@Column()
searchWord: string;
@Column()
algorithmId: number;
}
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { TestEntity } from './entities/test.entity';
import { TestController } from './test.controller';
@Module({
imports: [TypeOrmModule.forFeature([TestEntity], 'mongo')],
controllers: [TestController],
})
export class TestModule {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment