我正在使用这个RESTful应用程序接口,我想向服务器发送一个post请求,以便在数据库中创建一个文档。为此,我使用model.create方法。但是它让我在控制台UnhandledPromiseRejectionWarning: ValidationError: Product validation failed: seller: Please enter product seller, category: Please enter the product category, description: Please enter product description, name: Please enter product name中发送错误,我正在postman内部测试它。我的代码中有没有bug?我怎么才能解决这个问题。这是我的app.js文件
const express = require('express')
const mongoose = require('mongoose')
const bodyParser = require("body-parser");
const app = express()
app.use(bodyParser.urlencoded({extended: true}));
mongoose.connect('mongodb://localhost:27017/playDB', {useNewUrlParser: true, useUnifiedTopology: true})
const playSchema = new mongoose.Schema({
name: {
type: String,
required: [true, 'Please enter product name'],
},
price : {
type: Number,
required: [true, 'Please enter product price'],
},
description: {
type: String,
required: [true, 'Please enter product description']
},
category: {
type: String,
required: [true, 'Please enter the product category'],
},
seller: {
type: String,
required: [true, 'Please enter product seller']
},
stock: {
type: Number,
required: [true, 'Please enter product stock'],
}
})
const Product = mongoose.model('Product', playSchema)
//get all products
app.route("/products")
.post(async function(req, res, next){
const product = await Product.create(req.body);
res.send({
success: true,
product
})
})
app.listen(3000, function(){
console.log('server is running')
})
发布于 2021-09-11 14:04:20
我没有让express读取express格式。这就是它不起作用的原因
我所要添加的就是app.use(express.json()),然后它就可以工作了
https://stackoverflow.com/questions/69142335
复制相似问题