Nestjs中操作Mongodb数据库可以使用Nodejs封装的DB库,也可以使用Mongoose。下面我们主要给大家讲讲在Nestjs中使用Mongoose操作mongodb数据库
npm install --save @nestjs/mongoose mongoose npm install --save-dev @types/mongoose
在app.module.ts中配置数据库连接
import { Module } from '@nestjs/common'; import { MongooseModule } from '@nestjs/mongoose'; @Module({ imports: [MongooseModule.forRoot('mongodb://localhost/koa',{ useNewUrlParser: true })] }) export class ApplicationModule {}
import * as mongoose from 'mongoose'; export const ArticleSchema = new mongoose.Schema({ title: String, keywords:String, author: Number, status: String, });
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 {}
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(); } }