ค้นหาเว็บไซต์

node.js - การฉีดการเชื่อมต่อ mongodb ใน nestJs ไม่ทำงาน


ฉันกำลังพยายามเชื่อมต่ออย่างง่ายกับ localhost ของฉัน:

ฉันไม่ต้องการใช้ Models หรือ Schemas เพราะโครงสร้างข้อมูลเป็นแบบไดนามิกทั้งหมด ดังนั้นฉันจึงต้องการทำงานกับการเชื่อมต่อ Mongoose แบบเนทีฟ

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

วัตถุการเชื่อมต่อที่ฉันได้รับไม่มีคอลเล็กชันและไม่มีข้อมูล (บน Robo3T ของฉันมีคอลเล็กชันที่มีข้อมูล) บางอย่างเช่น:

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

ฉันทำอะไรผิดไปหรือ

คำตอบ #1

คุณยังจำเป็นต้องนำเข้าคอลเล็กชันแต่ละอันด้วยวิธี MongooseModule.forFeature

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

และจากนั้นคุณก็สามารถใช้มันได้

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();
  }
}

คุณสามารถหาข้อมูลเพิ่มเติมได้ที่นี่