1.安装依赖包
TypeScript
npm install --save @typegoose/typegoose
npm install --save mongoose
2.在man.ts中引入
TypeScript
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import * as mongoose from 'mongoose';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
//dbName数据库名称
await mongoose.connect('mongodb://localhost:27017/', { dbName: 'reactDataBase' })
.then(() => console.log('连接成功')).catch(err => console.log(err));
await app.listen(3000);
}
bootstrap();
3.定义模型
新建一个user.scheam.ts文件
TypeScript
import { prop, getModelForClass } from '@typegoose/typegoose';
class User {
@prop({ required: true })
public username: {
type: String,
default: ""
}
@prop({ required: true })
password: {
type: String,
default: ""
}
@prop()
avatar: {
type: String,
default: ""
}
@prop()
description: {
type: String,
default: ""
}
@prop()
sex: {
type: String,
default: "male"
}
}
export const UserModel = getModelForClass(User, {
//为模型取名,默认为类的名字+s
schemaOptions: { collection: 'users' },
})
4.在service中使用
TypeScript
import { Injectable } from '@nestjs/common';
//导入模型
import { UserModel } from "../Schema/user.schema"
import * as mongoose from 'mongoose';
@Injectable()
export class UserService {
async findOne(id) {
const res = await UserModel.aggregate([
{
$match: { _id: new mongoose.Types.ObjectId(id) }
}
])
console.log(res)
return res;
}
}
5.在controller中调用
TypeScript
import { Controller, Get, Post, Body, Patch, Param, Delete } from '@nestjs/common';
import { UserService } from './User.service';
@Controller('user')
export class UserController {
constructor(private readonly UerService: UserService) { }
@Get()
findOne() {
return this.UserService.findOne('661a45e5d371586eeb837e9a');
}
}
6.输出结果
