使用MongoDB
sonder 默认

使用mongodb数据库

  • 安装
1
cnpm install --save @nestjs/mongoose mongoose
  • 在app.module.ts中连接数据库
1
2
3
4
5
6
7
import { MongooseModule } from '@nestjs/mongoose';
@Module({
// blob本地数据库名
imports: [MongooseModule.forRoot('mongodb://127.0.0.1:27017/blob',{ useNewUrlParser : true })]
})
export class AppModule {}

  • article.module.ts使用
1
2
3
4
5
6
7
8
import { MongooseModule } from '@nestjs/mongoose';
import { ArticleSchema } from '../schemas/article.schema';
@Module({
// collection 如果不填则以Article建立一张表
imports: [MongooseModule.forFeature([{ name: 'Article', schema: ArticleSchema,collection:"article" }])]
})
export class ArticleModule {}

  • 配置Schema
1
2
3
4
5
6
7
import * as mongoose from 'mongoose';
export const ArticleSchema = new mongoose.Schema({
title: String,
keywords:String,
author: Number,
status: String,
});
  • 业务逻辑service
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import { Injectable } from '@nestjs/common';
import { Model } from 'mongoose';
import { InjectModel } from '@nestjs/mongoose';
import { CreatePostDTO } from './dto/create-post.dto';
import { Article } from './article.interface';

@Injectable()
export class NewsService {

constructor(@InjectModel('Article') private readonly articleModel: Model<Article>) {}

async getPosts(): Promise<Article[]> {
// .sort({_id:-1}) 倒序
const posts = await this.articleModel.find().sort({_id:-1});
return posts;
}

async getPost(postID): Promise<Article> {
const post = await this.articleModel
.findById(postID)
.exec();
return post;
}
}
  • 控制器定义api接口
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import { Controller, Post, UseGuards, Body, Get, HttpStatus, Res, Query } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { ArticleService } from './article.service';
import { CreatePostDTO } from './dto/create-post.dto';

@Controller('article')
export class ArticleController {
constructor( private readonly ariticleService: ArticleService){}

// 获取所有文章
@Get('getArticles')
// @UseGuards(AuthGuard('jwt'))
async getPosts(@Res() res) {
const posts = await this.ariticleService.getPosts();
return res.status(HttpStatus.OK).json(posts);
}
// 添加文章
@Post('addArticle')
// token验证
@UseGuards(AuthGuard('jwt'))
async addArticle(@Res() res, @Body() createPostDTO: CreatePostDTO){
const newPost = await this.ariticleService.addPost(createPostDTO);
return res.status(HttpStatus.OK).json({
message: "添加成功!!!",
status:200,
data: newPost
})
}

}

// http://localhost:3001/article/getArticles
  • 本文标题:使用MongoDB
  • 本文作者:sonder
  • 创建时间:2020-05-20 14:32:05
  • 本文链接:https://sonderss.github.io/2020/05/20/使用MongoDB/
 评论