【问题标题】:Injecting mongodb connection in nestJs not working在nestJs中注入mongodb连接不起作用
【发布时间】:2020-11-23 12:48:24
【问题描述】:

我正在尝试与我的本地主机进行简单连接:

我不想使用模型或模式,因为数据结构是完全动态的,所以我想使用原生 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

我做错了什么?

【问题讨论】:

  • 你连接到mongodb://localhost/nestjs看那里有收藏了吗?
  • 是的@JayMcDoniel,正如我所说,如果我与 Robo3T 连接,我可以看到所有集合和数据
  • 如果您不创建和提供模式,我不确定连接是否知道集合。您是否尝试过创建模式来映射数据库中的数据?

标签: node.js mongodb typescript mongoose nestjs


【解决方案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();
  }
}

你可以找到more information here

【讨论】:

  • 好的,我明白了,但是如果数据结构从一个文档到另一个文档不同,那么架构应该如何呢?无论架构属性如何,我都希望能够获取所有数据
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-09-05
  • 2020-07-22
  • 2020-11-23
  • 2014-06-17
  • 1970-01-01
  • 2021-04-13
相关资源
最近更新 更多