如何在NestJs中保存MongoDB中的API响应 [英] How to save api response in mongodb in NestJs
本文介绍了如何在NestJs中保存MongoDB中的API响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用NestJs作为后端服务,在那里我遇到了一些第三方API,并希望将响应保存在MongoDB中。我无法获取如何在MongoDB中保存数据,因为我有要保存的数据的DTO类。
以下是我的代码:
app.mode.ts
import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { UserModule } from './user/user.module';
@Module({
imports: [UserModule,
MongooseModule.forRoot('mongodb://localhost/status')],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
user.mode.ts
import { HttpModule } from '@nestjs/axios';
import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { ScheduleModule } from '@nestjs/schedule';
import { StatusSchema } from './schemas/status.schema';
import { UserController } from './user.controller';
import { UserService } from './user.service';
@Module({
imports:[HttpModule,
ScheduleModule.forRoot(),
MongooseModule.forFeature([{ name: 'Status', schema: StatusSchema }])],
controllers: [UserController],
providers: [UserService]
})
export class UserModule {}
status.schema.ts
import { Prop, Schema, SchemaFactory } from "@nestjs/mongoose";
import { Document } from "mongoose";
export type StatusDocument = Status & Document;
@Schema()
export class Status{
@Prop()
total:String;
}
export const StatusSchema = SchemaFactory.createForClass(Status);
status.dto.ts
export class StatusDto{
total:string;
}
user.service.ts
@Injectable()
export class UserService {
constructor(private httpService:HttpService,
private schedulerRegistry:SchedulerRegistry,
@InjectModel('Status') private readonly statusModel:Model<Status>){}
private readonly logger = new Logger(UserService.name);
async dynamicJob(){
this.logger.log("in main function");
const dat = await this.nameFun();
this.logger.warn(dat);
//Here I want to save the dat inside mongodb
}
nameFun = async () =>{
const url = 'https://reqres.in/api/unknown';
const result = await axios.get(url);
this.logger.log("In nameFun " + result.data.total);
return result.data.total;
}
}
有没有人告诉我如何在MongoDB内的上述函数中的指定位置添加数据。
推荐答案
以下是一个使用json placeholder数据的工作示例,我可以使用它进行测试,因为我不知道您的响应是什么样子。我只是将文本从响应的title
字段传递到Status
架构的total
字段。
UserService
的两个函数如下所示。
async dynamicJob() : Promise<Status> {
this.logger.log('in main function');
const dat = await this.nameFun();
this.logger.warn(dat);
const dto = { total: dat }; // creating dto in the form of your schema
this.logger.log(dto);
return await this.statusModel.create(dto); // saves and returns saved object
}
nameFun = async () => {
const url = 'https://jsonplaceholder.typicode.com/todos/2';
const result = await axios.get(url);
// you'll need to change this back to correct parsing of your actual response
this.logger.log('In nameFun ' + result.data.title);
return result.data.title;
};
则您的UserController
中的相应函数将如下所示,无论您要使用哪个端点。这里我只是使用from-api
。
@Get('from-api')
async getFromApi() : Promise<Status> {
return this.userService.dynamicJob();
}
从此终结点获取请求
http://localhost:3000/user/from-api/
返回Mongo中新创建的文档
{
"total": "quis ut nam facilis et officia qui",
"_id": "622a1a6e990efa55c984dc4b",
"__v": 0
}
这篇关于如何在NestJs中保存MongoDB中的API响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文