Injecting mongodb connection in nestJs not working

Viewed 3940

I'm trying to do a simple connection with my localhost:

I don't want to use Models or Schemas because the data structure is totally dynamic so I want to work with the native Mongoose Connection

app.module.ts

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

@Module({
  imports: [MongooseModule.forRoot('mongodb://localhost/nestjs')],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

app.service.ts

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

@Injectable()
export class AppService {

  constructor(@InjectConnection() private connection: Connection){}

  getConnection() {
    return this.connection;
  }
}

app.controller.ts

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

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

  @Get()
  async getConnection() {
    const connection  = await this.appService.getConnection();
    return connection;
  }
}

The connection object I recieve has no collections and no data (on my Robo3T I have collections with data) Something like:

base:Mongoose {connections: Array(2), models: {…}, modelSchemas: {…}, options: {…}, _pluralize: ƒ}
client:MongoClient {_events: {…}, _eventsCount: 2, _maxListeners: undefined, s: {…}, topology: NativeTopology}
collections:{}
config:{autoIndex: true}
db:Db {_events: {…}, _eventsCount: 3, _maxListeners: undefined, s: {…}, serverConfig: <accessor>}
host:'localhost'
id:1
models:{}
name:'nestjs'
options:null
otherDbs:(0) []
pass:undefined
plugins:(0) []
port:27017

What am I doing wrong?

1 Answers

You need also import each collection with MongooseModule.forFeature method.

@Module({
  imports: [
    MongooseModule.forRoot('mongodb://localhost/nestjs'),
    MongooseModule.forFeature([{ name: 'CollectionName', schema: CollectionSchema }]),
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

And then you could use it

import { Model } from 'mongoose';
import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';

@Injectable()
export class AppService {

  constructor(@InjectModel('CollectionName') private model: Model<any>){}

  findAll() {
    return this.model.find().exec();
  }
}

You can find more information here

Related