我目前正在尝试创建一个事件并将其存储在我的mongo数据库中。以下是我当前的事件架构。
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
//blueprint for each new entry in the db
var eventSchema = new Schema({
eventName: {type:String},
eventDate: {type:String},
eventPlace:{type:String},
eventPrice: {type: Number}
});
module.exports = mongoose.model('Event', eventSchema);
这是我的user.js文件中的创建功能代码
// /route for new event
router.get('/newEvent', function (req,res,next) {
var messages = req.flash('error');
res.render('user/newEvent',{csrfToken: req.csrfToken(),messages: messages, hasErrors: messages.length >0});
});
//route for new event save
router.get('/createEvent', function(req, res, next) {
var event = new Event();
eventName = req.body.eventName;
eventDate = req.body.eventDate;
eventPlace = req.body.eventPlace;
eventPrice = req.body.eventPrice;
event.save(function(err) {
if(err) return next(err);
res.json({ message : 'Success!'});
});
});
这是我在newEvent.hbs文件中创建新事件的表单。
<div class = "row">
<div class="col-md-4 col-md-offset-4">
<h1> Create a new Event</h1>
{{#if hasErrors}}
<div class=alert alert-danger">
{{# each messages}}
<p>{{this}}</p>
{{/each}}
</div>
{{/if}}
<form action="/user/newEvent" method="post">
<div class="form-group">
<label for="eventName">Event Name</label>
<input type="text" id="eventName" name="eventName"class="form-control">
</div>
<div class="form-group">
<label for="eventDate">Event Date</label>
<input type="text" id="eventDate" name="eventDate" class="form-control">
</div>
<div>
<label for="eventPlace">Place of Event</label>
<input type="text" id="eventPlace" name="eventPlace" class="form-control">
</div>
<div>
<label for="eventPrice">Price of Event: €</label>
<input type="text" id="eventPrice" name="eventPrice" class="form-control">
</div>
<input type="hidden" name="_csrf" value="{{ csrfToken}}">
<a href="createEvent" class="pull-right btn btn-success" role="button">Create Event</a>
</form>
</div>
到目前为止,当我运行代码时,我收到一条错误,指出eventName,eventPlace,eventDate和eventPrice是必需的并且尚未输入但是当我删除&#34; required:true&#34;从事件模式中创建一个新事件,但数据库中没有存储数据。
答案 0 :(得分:0)
1-您没有正确保存事件eventName = req.body.eventName
目前你正在保存空对象,这就是为什么当你删除它时需要保存空数据。
2-您还在使用req.body
来获取您应该使用的router.post
检查以下代码
router.post('/createEvent', function(req, res, next) {
var event = new Event({
eventName:req.body.eventName,
eventDate : req.body.eventDate,
eventPlace : req.body.eventPlace,
eventPrice : req.body.eventPrice
});
event.save(function(err) {
if(err) return next(err);
res.json({ message : 'Success!'});
});
});