i’m new to nodeJS. am trying a use post request to get the information the user post but am getting an error: TypeError: Cannot read properties of undefined (reading ‘title’). please what am i doing wrong here.
here’s my code
const express = require("express")
const app = express()
const mongoose = require("mongoose")
const Schema = mongoose.Schema;
const BlogPost = new Schema({
title:{
type: String,
required: true
},
content: {
type: String,
required: true
},
body: {
type: String,
required: true
}
})
const Blog = mongoose.model("Blog", BlogPost)
module.exports = Blog;
app.post("/blogs", (req, res) => {
const blogs = new Blog({
title:req.body.title,
content: req.body.content,
body: req.body.body,
})
blogs.save()
.then(result => console.log(result))
.catch(err => console.log(err))
})
2
Answers
You may not get title from
req.body.title
that’s why when you save this doc to mongodb it will throw this error.For solution, you must check
req.body.title
before saving data into mongodb,Otherwise, simply REMOVE required: true from schema
To make this code to workable condition for that add
app.use(express.json())
As we are accepting http request body value from postman , so that it will parse our http request into json payload,
Hence we can access the body parameters value by req.body..
enter image description here
enter image description here