Actually I am trying to push a new nested array inside an array through update request for an API. I am using all necessary middleware such as app.use(express.json())
and app.use(express.urlencoded({extended: true}));
and also the multipart/form-data
in the postman header but still I am getting the req.body
undefined.
Below is the Update request code
const Update =async (req,res)=>{
const _id = req.params.id
const {Episodes} = req.body
try{
const UpdatedPodcast = await Podcasts.updateOne({
_id
},
{
$push:{
Episodes:[{
Episodes
}]
}
},
{
upsert:true,
new:true
}
)
console.log(Episodes)
// console.log(data)
res.send(UpdatedPodcast)
}catch(err){
res.status(500).json({
message:"Error in updating the data"
})
console.log(err)
}
}
Below is the schema for API data
const mongoose = require('mongoose')
const PodcastSchema = new mongoose.Schema({
CategoryName:String,
Episodes:[
{
EpisodeNo:Number,
EpisodeName:String,
EpisodeDescription:String,
imageurl:String
}
]
},
{
timestamps:true
})
module.exports = mongoose.model('PodcastSchema',PodcastSchema)
Below is the screenshot of POSTMAN request
I have tried to access the Episodes array through different method but still getting req.body undefined. Can someone help me to find solution to this problem.
2
Answers
When looking on your screenshot, I notice that there a no field representing the
Episodes
field which is the array your looking for.So basically, it’s normal that your
const {Episodes} = req.body
give your null.Note that it’s not the req.body null, but the
{Episodes}
field which is absent.What I suggest:
Episodes
field of a podcast. These endpoint can be:I think, the different controller for the above route are just dealing with array stuffs.
In my sample,
[ID]
is the podcast id and[IndexOfTheEpidode]
is the index of the target episode in your podcast’s episodes array.Now you can use approximatively what is in your screen.
make sure that you have included the express.json() middleware before your route handlers and before your route definition and also ensure that you are sending the request with the correct Content-Type header set to application/json. In Postman, make sure to select "raw" and "JSON (application/json)" options for the request body.