连接MongoDb(Mongooes)
原创2026/3/5小于 1 分钟
安装
npm i @nestjs/mongoose mongoose配置
import { Module } from '@nestjs/common'
import { AppController } from './app.controller'
import { MongooseModule } from '@nestjs/mongoose'
import { AppService } from './app.service'
@Module({
imports: [MongooseModule.forRoot(`mongodb://47.92.214.203/jiamei`)],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}模型注入
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose'
import { HydratedDocument } from 'mongoose'
export type CatDocument = HydratedDocument<App>
@Schema()
export class App {
@Prop()
userName: string
@Prop()
passWord: string
@Prop()
isActive: string
}
export const AppSchema = SchemaFactory.createForClass(App)使用
app.module.ts
import { Module } from '@nestjs/common'
import { AppController } from './app.controller'
import { MongooseModule } from '@nestjs/mongoose'
import { AppService } from './app.service'
import { App, AppSchema } from './app.entity'
@Module({
imports: [
MongooseModule.forRoot(`mongodb://47.92.214.203/jiamei`),
MongooseModule.forFeature([{ name: App.name, schema: AppSchema }]),
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}app.controller.ts
import { Controller, Get } from '@nestjs/common'
import { AppService } from './app.service'
@Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
@Get('register')
register() {
return this.appService.register()
}
}app.service.ts
import { Injectable } from '@nestjs/common'
import { App } from './app.entity'
import { InjectModel } from '@nestjs/mongoose'
import { Model } from 'mongoose'
@Injectable()
export class AppService {
constructor(@InjectModel(App.name) private readonly app: Model<App>) {}
async register() {
const createdUser = new this.app({
userName: 'admin',
passWord: '123456',
isActive: false,
})
const data = await createdUser.save()
return {
code: 200,
msg: '注册成功',
result: data,
}
}
}至此,本章节的学习就到此结束了,如有疑惑,可对接技术客服进行相关咨询。