【发布时间】: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