Home > OS >  Nest js not populating db with form data
Nest js not populating db with form data

Time:11-15

I have set up a blog where data is sent to a endpoint and ends up in a Mongo DB database. Im using mongoose and am very new to nest.js so I would some help if possible

blog.service.ts:

async addPost(CreatePostDTO: CreatePostDTO): Promise<Post> {
        const newPost = await new this.postModel(CreatePostDTO);
        return newPost.save()
    }

blog.controller.ts:

@Post('/post')
    async addPost(@Res() res, @Body() createPostDTO: CreatePostDTO) {
        const newPost = await this.blogService.addPost(createPostDTO);
        return res.status(HttpStatus.OK).json({
            message: "Post has been submitted successfully!",
            post: newPost
        })
    }

create-post.dto.ts

export class CreatePostDTO {
    readonly title: string;
    readonly description: string;
    readonly body: string;
    readonly author: string;
    readonly date_posted: string;
}

Schema:

import * as mongoose from 'mongoose'

export const BlogSchema = new mongoose.Schema({
    title: String,
    description: String,
    body: String,
    author: String,
    date_posted: String
})

Payload: payload

I then open postman and send to localhost:3000/blog/post with formdata that follows the above required params

On return I get

{
    "message": "Post has been submitted successfully",
    "post": {
        "_id": "637376ca3aee6376a7c373d7",
        "__v": 0
    }
}

and no data is saved but a new document is created

CodePudding user response:

You should change your postman body to send JSON data instead of form-data (by selecting raw and then pick JSON.

Otherwise you would need to include some handler in order to handle data posted as multipart/form-data (see https://docs.nestjs.com/techniques/file-upload#file-upload).

Changing it should result in createPostDTO parameter being set.

  • Related