0

I am using NestJs as a backend service where I am hitting some third party API and want to save response in MongoDB. I am unable to get how can I save data in MongoDB as I have DTO class for the data I want to save.

Below is my code:

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;
}
} 

How can I add data inside MongoDB at specified place in above function?

1 Answer 1

1

Here's a working example with json placeholder data that I can test with since I don't know what your response looks like. I'm just passing in the text from the title field of the response into the total field of your Status schema.

Your 2 functions of UserService would look like this.


  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;
  };

Then the corresponding function in your UserController would look something like this, which whatever endpoint you want to use. Here I'm just using from-api.

  @Get('from-api')
  async getFromApi() : Promise<Status> {
    return this.userService.dynamicJob();
  }

Get request from this endpoint

http://localhost:3000/user/from-api/

returns the newly created document in Mongo

{
  "total": "quis ut nam facilis et officia qui",
  "_id": "622a1a6e990efa55c984dc4b",
  "__v": 0
}
Sign up to request clarification or add additional context in comments.

1 Comment

That's working absolutely perfect thanks for an example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.