实际上,我在我的API中更新了一个数组,在更新数组之后,我只得到了mongodb的默认id。虽然定义了req.body,但似乎没有定义req.body.something。而且我正确地使用了所有的中间件,比如body-parser
这是server.js
代码
/* eslint-disable no-unused-vars */
/* eslint-disable no-undef */
const mongoose = require('mongoose')
const express = require('express')
const cors = require('cors')
// const bodyParser = require('body-parser')
const userRouters = require('./routes/user.js')
const podcastRouter = require('./routes/pocasts.js')
// const methodOverride = require('method-override')
const port = 8080
const app = express()
// app.use(bodyParser.json())
app.use(express.json())
app.use(express.urlencoded({extended: true}));
// app.use(express.methodOverride());
app.use(cors({
credentials: true,
}))
//routes
app.use('/',userRouters)
app.use('/api/podcasts' , podcastRouter)
app.post('/api/podcasts',(req,res)=>{
res.send("This is the api page")
})
app.post('/login',(req,res)=>{
res.send("This is the login page")
})
app.post('/signup',(req,res)=>{
res.send("This is the signup page")
res.json(req.body)
})
const DB = "mongodb+srv://fk28:farhankhan123@cluster0.fq2ibrs.mongodb.net/test"
mongoose.connect(DB , {
useNewUrlParser:true,
useUnifiedTopology:true
}).then(()=>{
console.log("connection successful")
}).catch((err)=>{
console.log(err)
})
app.listen(port , ()=>{
console.log("listening to port",port)
})
您可以看到我已经使用了bodyparser和其他中间件。也将它们放置在路由器之前。
这是update
代码
const Update =async (req,res)=>{
const _id = req.params.id
// const { ...data } = req.body
const bodycontent = req.body
try{
const UpdatedPodcast = await Podcasts.updateOne({
_id
},
{
$push:{
Episodes:[{
EpisodeNo:bodycontent.EpisodeNo,
EpisodeName:bodycontent.EpisodeName,
EpisodeDescription:bodycontent.EpisodeDescription
}]
}
},
{
upsert:true,
new:true
}
)
console.log(req.body.EpisodeNo,req.body.EpisodeName,req.body.EpisodeDescription)
console.log(req.body)
res.send(UpdatedPodcast)
}catch(err){
res.status(500).json({
message:"Error in updating the data"
})
}
}
我在这里安慰请求体,也安慰请求体什么的
这是consolled输出
undefined undefined undefined
{
Episodes: {
EpisodeNo: 3,
EpisodeName: 'All About Cooking',
EpisodeDescription: 'Cooking is fun'
}
}
这是API的输出
{
"_id": "646e2cc2040b492346842b34"
},
我正在使用Postman进行请求
这是 Postman 的请求
{
"Episodes":
{
"EpisodeNo": 3,
"EpisodeName": "All About Cooking",
"EpisodeDescription": "Cooking is fun"
}
}
我已经使用了所有的中间件,但也得到了req.body.一些未定义的东西。我期待在我只得到默认的mongodb id i的地方,我也应该得到更新的数据。
1条答案
按热度按时间shyt4zoc1#
你的EpisodeNo,EpisodeName,EpisodeDescription是一个嵌套的对象属性,因为你在请求中传递了嵌套的JSON。
因此,改为像这样获取值:
const {EpisodeNo, EpisodeName, EpisodeDescription} = req.body.Episodes
也可以不嵌套地传入每个属性。
{ "EpisodeNo": 3, "EpisodeName": "All About Cooking", "EpisodeDescription": "Cooking is fun" }