Node.js mongoose需要true req.body.name{}
如果我将required设置为false,它将成功地在MongoDB数据库中创建一个具有一个id的对象。我有时会感到困惑,如果需要,请检查我的配置文件。我认为这是一件小事。如果你需要更多信息,只需评论Node.js mongoose需要true req.body.name{},node.js,express,Node.js,Express,如果我将required设置为false,它将成功地在MongoDB数据库中创建一个具有一个id的对象。我有时会感到困惑,如果需要,请检查我的配置文件。我认为这是一件小事。如果你需要更多信息,只需评论 app.js var express = require('express'); var bodyParser = require('body-parser'); var product = require('./routes/product'); // Imports routes for th
app.js
var express = require('express');
var bodyParser = require('body-parser');
var product = require('./routes/product'); // Imports routes for the products
var app = express();
var mongoose = require('mongoose'); // Set up mongoose connection
var dev_db_url = 'mongodb://localhost/Product';
var mongoDB = process.env.MONGODB_URI || dev_db_url;
mongoose.connect(mongoDB, {useNewUrlParser: true, useUnifiedTopology: true});
mongoose.Promise = global.Promise;
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use('/products', product);
var port = 3002;
app.listen(port, () => {
console.log('Server is up on port numbner ' + port);
});
model.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ProductSchema = new Schema({
name: {type: String, required: true, max: 100},
price: {type: Number, required: true},
});
module.exports = mongoose.model('Product', ProductSchema);
controller.js
var Product = require('../models/product');
//Simple version, without validation or sanitation
exports.test = function (req, res) {
res.send('Greetings from the Test controller!');
};
exports.product_create = function (req, res, next) {
var product = new Product(
{
name: req.body.name,
bags: req.body.bags
}
);
console.log(JSON.stringify(req.body))
product.save(function (err) {
if (err) {
return next(err);
}
res.send('Bags Created successfully')
})
};
路由器.js
var express = require('express');
var router = express.Router();
// Require the controllers WHICH WE DID NOT CREATE YET!!
var product_controller = require('../controllers/product');
// a simple test url to check that all of our files are communicating correctly.
router.get('/test', product_controller.test);
router.post('/create', product_controller.product_create);
module.exports = router;
HTTP POST:
验证错误:产品验证失败:名称:路径
name
is
必需的
你能帮忙吗?
谢谢 如何创建和保存产品对象?@mauliksakida Product.save(function..controller.I是否缺少其他内容?您还更改了什么?我得到了{}从console.log.ValidationError:Product validation failed:name:Path
name
是必需的。第二个参数相同。从上面的示例中,我使用的是数据名称和价格,这就是为什么我将req.body.bags
从您的更改为'req.body.price'。两者都是{}…您如何从postman获取并接收值?无论我发布的结果始终相同,如果您在console.log(req.params)
和console.log(req.body)中出错,您都将得到结果{}
。请确保这样做没有错,因为我首先尝试了上面所写的内容,得到了预期的结果。我以前做过这种API并使用过Postman,但这次对req.body或req.params都不起作用。我现在退出并接受您的答案。感谢您的输入