当我想将文档添加到mongoDB数据库时,我试图找出究竟发生了什么。
当我尝试添加文档时,我收到此错误:
{
"errors": {
"name": {
"message": "Path `name` is required.",
"name": "ValidatorError",
"properties": {
"type": "required",
"message": "Path `{PATH}` is required.",
"path": "name"
},
"kind": "required",
"path": "name"
}
},
"message": "Product validation failed",
"name": "ValidationError"
}
所以我使用Express Js和Mongoose来执行此操作。 在我的模型中:product.js
var mongoose = require('mongoose');
var productSchema = new mongoose.Schema({
name: {type: String, required: true},
category: {type: String, default: ''},
price: { type: Number, default: 0},
picture: { type: String},
quantity: {type: Number, default: 0},
status: {
type: String,
enum: ['pending', 'In Progress', 'Cancelled', 'Done'],
default: 'pending'
},
date: { type: Date, default: Date.now},
description: { type: String},
owner: {type: String}
});
var Product = mongoose.model('Product', productSchema);
module.exports = Product;
在我的api路由中,当我定义执行此操作的路径时: index.js
var express = require('express');
var router = express.Router();
var productCtrl = require('../controllers/productCtrl');
router.get('/products', productCtrl.getAllProducts);
router.get('/products/:productId', productCtrl.readProduct);
router.post('/products', productCtrl.createProduct);
router.delete('/products/:productId', productCtrl.removeProduct);
router.put('/products/:productId', productCtrl.updateProduct);
module.exports = router;
最后,在我的控制器文件中: productCtrl.js
var Product = require ('../models/products');
var sendJsonResponse = function(res, status, content) {
res.status(status);
res.json(content);
}
module.exports.createProduct = function (req, res){
Product
.create({
name: req.body.name,
category: req.body.category,
price: req.body.price,
picture: req.body.picture,
quantity: req.body.quantity,
status: req.body.status,
date: req.body.date,
description: req.body.description,
owner: req.body.owner
}, function createProduct(err, product){
if(err){
sendJsonResponse(res, 404, err);
return;
}
else {
sendJsonResponse(res, 201, product);
}
});
}
行为除外是我应该以json格式返回产品文档
关于我的环境,我使用:
node.js version: 6.9.4
mongodb version: 3.4.4
express version: ~4.13.4
mongoose version: ^4.9.8
我真的需要帮助人
答案 0 :(得分:1)
该异常意味着模型中的字段“name”是必需的(您设置required = true),但未提供,表示您将null或undefined传递给它
.create({
name: req.body.name,
req.body.name可能未定义。检查您的POST操作并尝试console.log(req.body)以查看它是否已填充。
答案 1 :(得分:1)
该例外意味着该字段" name"在你的模型中是必需的(你设置required = true),检查你的req.body.name POST动作。
express-validator模块,用于执行数据的验证和清理,以避免此问题。像这样:
Vnew = Vold + M * N
你可以试试这个:
productCtrl.js
req.checkBody('name', 'Product name required').notEmpty();
var errors = req.validationErrors();
//Run the validators
var errors = req.validationErrors();
if (errors) {
//If there are errors data form invalid
res.send('');
return;
}
else {
// Data from form is valid.
}