Nest.js操控MongoDB的方法

一、安装 nestjs/mongoose 以及 mongoose 模块

Nest 操作 Mongodb 官方文档:https://docs.nestjs.com/techniques/mongodb

1
npm install --save @nestjs/mongoose mongoose

二、配置数据库连接地址

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

1
2
3
4
5
6
7
8
import { Module } from '@nestjs/common'; 
import { MongooseModule } from '@nestjs/mongoose';

@Module({
imports: [MongooseModule.forRoot('mongodb://localhost/koa',{ useNewUrlParser: true })]
})

export class ApplicationModule {}

三、配置 Schema

1
2
3
4
5
6
7
8
import * as mongoose from 'mongoose'; 

export const ArticleSchema = new mongoose.Schema({
title: String,
keywords:String,
author: Number,
status: String,
});

四、在控制器对应的 Module 中配置 Model

1
2
3
4
5
6
7
8
9
10
11
12
import { Module } from '@nestjs/common'; 
import { NewsController } from './news.controller';
import { NewsService } from './news.service';
import { ArticleSchema } from './schemas/article.schema';
import { MongooseModule } from '@nestjs/mongoose';

@Module({
imports: [MongooseModule.forFeature([{ name: 'Article', schema: ArticleSchema,collection:"article" }])], controllers: [NewsController],
providers: [NewsService]
})

export class NewsModule {}

五、在服务里面使用 InjectModel 获取数据库 Model 实现 操作数据库

1
2
3
4
5
6
7
8
9
10
import { Injectable } from '@nestjs/common'; 
import { InjectModel } from '@nestjs/mongoose';

@Injectable()
export class NewsService {
constructor(@InjectModel('Article') private readonly articleModel) {}
async findAll() {
return await this.articleModel.find().exec();
}
}
作者

vear

发布于

2019-11-20

更新于

2022-01-03

许可协议

评论