如何在 NestJs 的 MongoDB 中保存 api 响应
How to save api response in MongoDB in NestJs
我正在使用 NestJs 作为后端服务,我正在访问一些第三方 API 并希望在 MongoDB 中保存响应。我无法获得如何在 MongoDB 中保存数据,因为我有 DTO class 用于我要保存的数据。
下面是我的代码:
app.module.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.module.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
的 2 个函数看起来像这样。
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/
returns Mongo
新建文档
{
"total": "quis ut nam facilis et officia qui",
"_id": "622a1a6e990efa55c984dc4b",
"__v": 0
}
我正在使用 NestJs 作为后端服务,我正在访问一些第三方 API 并希望在 MongoDB 中保存响应。我无法获得如何在 MongoDB 中保存数据,因为我有 DTO class 用于我要保存的数据。
下面是我的代码:
app.module.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.module.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
的 2 个函数看起来像这样。
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/
returns Mongo
新建文档{
"total": "quis ut nam facilis et officia qui",
"_id": "622a1a6e990efa55c984dc4b",
"__v": 0
}