0

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

1
  • 1
    Can you include the actual payload, that was used + the schema definition of your Post model? Commented Nov 15, 2022 at 12:32

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Perfection! Makes sense and I thought it might be simple!

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.