代码工作正常(用于获取请求),直到我想在 mongoDb 中通过 post 请求保存数据,当我使用 router.post(productController.postProduct) 我收到此错误:无法读取未定义的属性“名称””
导出函数为:
exports.postProduct=async (req,res)=>{
try{
const newProduct=new Products()
newProduct.save({
name: req.body.name,
price:req.body.price
})
res.status(201).json({
status:'success',
data:{
tour:newProduct
}
})}
catch(err){
res.status(404).json({
status:'fail',
message:err.message
})
}
}
`游览模型是
const mongoose=require('mongoose');
const slugify=require("slugify")
const productSchema=new mongoose.Schema({
name:{
type:String,
unique:true,
required:[true,"A Product must have name"],
maxLength:[40,"A Product name mus havr less than or equal to 40"],
minLength:[10,"A Product name must have atleast 10 characherts"],
},
slugify:{
type:String,
},
ratingAverage:{
type:Number,
default:4.5,
min:[1,"The rating must begreater than 0"],
max:[5,"The rating must be less than 5"],
},
ratingQuantity:{
type:Number,
default:0
},
price:{type:Number,
required:[true,"A Product must have price"]
},
priceDiscount:{
type:Number,
},
summary:{
type:String,
trim:true
},
description:{
type:String,
trim:true
},
images:[String],
createdAt:{
type:Date,
default:Date.now()
},
startDate:[Date],
},
)
而 app.js 是:
const express=require('express');
const fs=require("fs")
const app=express()
const mongoose=require("mongoose")
const dotenv=require("dotenv")
dotenv.config({path:"./process.env"})
const morgan =require("morgan")
const productsRoute=require("./Routes/productRoutes")
const DB=process.env.DATABASE.replace(
"<password>",
process.env.DATABASE_PASSWORD
)
mongoose.connect(DB,
{
useNewUrlParser:true,
useCreateIndex:true,
useFindAndModify:false,
useUnifiedTopology: true
})
.then(console.log("DB connection successfull"))
app.use(morgan('dev'))
var port=3000
app.listen(port,()=>{
console.log(`App is running on the port ${port}`);
})
app.use("/api/v1/products",productsRoute)
除了 post 请求外,所有其他 HTTP 似乎都可以正常工作
答案 0 :(得分:0)
尝试将这个 app.use(express.urlencoded({extended:false}))
放在 app.js 中的所有路由之上