nestjs连接并操作mongodb数据库

安装nestjs/mongoose 以及mongoose模块

cnpm install --save @nestjs/mongoose mongoose

配置数据库连接地址

在app.module.ts中配置数据库连接

import { AppController } from './modules/app/app.controller';
import { StudentsModule } from './modules/students/students.module';

@Module({
  imports:[MongooseModule.forRoot('mongodb://127.0.0.1:27017/students', {useNewUrlParser: true})]
})
export class AppModule {}

配置Schema

配置schema需要和数据库字段对应,用来操作数据库

import * as mongoose from 'mongoose';

export const StudentsSchema = new mongoose.Schema({
    name: String,
    age: Number,
    sex: String
})

在使用的控制器对应的Module中配置Model

import { Module } from '@nestjs/common';
import { StudentsController } from './students.controller';
import { MongooseModule } from '@nestjs/mongoose';
import { StudentsSchema } from 'src/schema/students.schema'; // 定义的schema模型
import { StudentsService } from './students.service';

@Module({
  imports: [MongooseModule.forFeature([
    {
      name: 'Students', // 需要个schema名称对应
      schema: StudentsSchema, // 引入的schema
      collection: 'students' // 数据库名称
    }
  ])],
  controllers: [StudentsController],
  providers: [StudentsService]
})
export class StudentsModule {}

定义服务操作数据库

import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
 
@Injectable()
export class StudentsService {
    constructor(
        @InjectModel('Students') private readonly studentsModel
    ) {}

    async studentsInfo() {
        return await this.studentsModel.find().exec();
    }
}

在对应的控制器中调用服务

import { Controller, Get } from '@nestjs/common';
import { StudentsService } from './students.service';

@Controller('students')
export class StudentsController {

    constructor(private readonly studentsService: StudentsService) {}

    @Get()
    index() {
        return this.studentsService.studentsInfo();
    }
}

浏览器测试请求

在这里插入图片描述

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值