nest中如何使用mogodb
安装
- 安装MongoDB驱动程序:
通过运行以下命令来安装
mongodb驱动程序:
$ npm install --save @nestjs/mongoose mongoose
- 创建数据库连接: 创建一个数据库连接的提供者,并将其添加到的模块中。例如:
import { MongooseModule } from '@nestjs/mongoose';
@Module({
imports: [
MongooseModule.forRoot('mongodb://localhost/nestjs'),
],
})
export class AppModule {}
- 创建模型:
以使用
@Schema()装饰器创建一个模型,并使用@Prop()装饰器定义模型的属性。例如:
@Schema()
export class Cat {
@Prop()
name: string;
@Prop()
age: number;
}
export const CatSchema = SchemaFactory.createForClass(Cat);
- 注册模型: 在模块中注册模型,以便它可以在其他地方使用。例如:
import { MongooseModule } from '@nestjs/mongoose';
import { Cat, CatSchema } from './schemas/cat.schema';
@Module({
imports: [
MongooseModule.forFeature([{ name: Cat.name, schema: CatSchema }]),
],
})
export class CatsModule {}
MongoDB操作的详细说明和示例代码
- 创建文档(Create):
要创建一个新的文档(即数据库中的一条记录),可以使用模型的
create方法。以下是一个示例:
import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { Cat, CatDocument } from './schemas/cat.schema';
@Injectable()
export class CatsService {
constructor(@InjectModel(Cat.name) private catModel: Model<CatDocument>) {}
async create(catDto: CatDto): Promise<Cat> {
const createdCat = new this.catModel(catDto);
return createdCat.save();
}
}
以上示例中,Cat是一个Mongoose模型,CatDto是创建新文档所需的数据传输对象。
- 读取文档(Read):
要从数据库中读取文档,可以使用模型的
find、findOne或findById方法。以下是一些示例:
async findAll(): Promise<Cat[]> {
return this.catModel.find().exec();
}
async findOne(id: string): Promise<Cat> {
return this.catModel.findById(id).exec();
}
async findByName(name: string): Promise<Cat> {
return this.catModel.findOne({ name }).exec();
}
以上示例中,findAll方法返回所有文档,findOne方法根据ID查找单个文档,findByName方法根据名称找到文档。
- 更新文档(Update):
要更新数据库中的文档,可以使用模型的
findByIdAndUpdate方法。以下是一个示例:
async update(id: string, catDto: CatDto): Promise<Cat> {
return this.catModel.findByIdAndUpdate(id, catDto, { new: true }).exec();
}
以上示例中,update方法根据ID更新指定文档,并返回更新后的文档。
- 删除文档(Delete):
要从数据库中删除文档,可以使用模型的
findByIdAndRemove方法。以下是一个示例:
async remove(id: string): Promise<Cat> {
return this.catModel.findByIdAndRemove(id).exec();
}
以上示例中,remove方法根据ID删除指定文档,并返回被删除的文档。
Ending
完结撒花