Я пытаюсь отправить форму для создания новой встречи в моей базе данных монго. Когда форма отправляется, я получаю сообщение об ошибке проверки, говорящее мне, что определенные поля являются обязательными. У меня есть console.logged поля из формы (как вы можете видеть в разделе «Контроллеры»), и они пусты. Я попытался отследить процесс отправки, но понятия не имею, где форма теряет информацию. В настоящее время у меня есть точно такая же установка для отправки новой машины в мою базу данных, и она работает отлично. Те же самые console.logs в моем контроллере представления автомобиля распечатывают новый объект автомобиля. Я предоставил свою маршрутизацию, модель встречи, контроллеры и код формы ниже. Я успешно достиг console.logs в моем контроллере, поэтому я не думаю, что это проблема маршрутизации. Я также включил точное сообщение об ошибке, которое я получаю в конце этого поста. Я считаю, что форма теряет все данные где-то между отправкой и проверкой, но я не знаю, как это отладить, и совершенно не понимаю, как решить эту проблему.
Маршрутизация:
const express = require('express');
const router = express.Router();
const appts = require('../controllers/appointments');
const catchAsync = require('../utils/catchAsync');
const { isLoggedIn, isAuthor } = require('../middleware');
const Appt = require('../models/appointments');
router.route('/')
.get(catchAsync(appts.index))
.post(catchAsync(appts.createAppt));
router.get('/new',appts.renderNewForm);
module.exports = router;
Контроллер:
const Appt = require('../models/appointments');
module.exports.createAppt = async (req,res) =>{
const appt = new Appt(req.body.appt);
console.log("Body: ",req.body);
console.log("Body: ",req.body.appt);
console.log("appt: ",appt);
//campground.author = req.user._id;
await appt.save();
req.flash('success', 'Successfully sent! Thank you for scheduling some time to meet with us, see you soon!');
res.redirect(`/cars`);
}
Модель:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const ApptSchema = new Schema({
name:String,
email:{
type:String,
required: true
},
phone:{
type:Number,
required: true
},
date:{
type:Date,
required: true
},
time:{
type:String,
required: true
},
interests: String,
scheduleTime:Date
});
module.exports = mongoose.model('Appointment',ApptSchema);
Форма:
<% layout('layouts/boilerplate')%>
<div class="display-3 text-center">SCHEDULE AN APPOINTMENT ONLINE:</div>
<div class="row">
<div class="col-md-6 offset-md-3">
<form action="/appointments" method="POST" novalidate class="validated-form" enctype="multipart/form-data">
<div class="mb-3">
<label class="form-label" for="name">Name</label>
<input class="form-control" type="text" id="name" name="appt[name]" required>
<div class="valid-feedback">
Looks good!
</div>
</div>
<div class="mb-3">
<label class="form-label" for="email">Email</label>
<input class="form-control" type="email" id="email" name="appt[email]" required>
<div class="valid-feedback">
Looks good!
</div>
</div>
<div class="mb-3">
<label class="form-label" for="phone">Phone Number:</label>
<input class="form-control" type="tel" id="phone" name="appt[phone]" pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}" required>
<small>Format: 555-456-7890</small>
</div>
<div class="mb-3">
<label for="date" class="form-label">Please Enter your Prefered Date</label>
<input class="form-control" type="date" id="date" name="appt[date]" required>
</div>
<div class="mb-3">
<label for="time" class="form-label">Please Select a Time Slot</label>
<select class="form-control" id="time" name="appt[time]" required>
<option value="morning">Morning (10-11:30am)</option>
<option value="afternoon">Afternoon (12-2:30pm)</option>
<option value="evening">Evening (3-4:30pm)</option>
</select>
</div>
<div class="mb-3">
<label class="form-label" for="interests">What are you interested in?</label>
<textarea class="form-control" type="text" id="interests" name="appt[interests]" placeholder="example: All wheel drive family car with great mileage." required></textarea>
<div class="valid-feedback">
Looks good!
</div>
</div>
<div class="mb-3">
<label><strong>Appoitnment Request will be sent to Just Cars. You will shortly receive an email with a specified time within your time slot for your appointment.</strong></label>
</div>
<div class="mb-3 text-center">
<button class="btn btn-success">Request Appointment</button>
</div>
</form>
</div>
</div>
<div class="container">
<div class="row text-center" style="margin-top:40px; margin-bottom:50px;">
<div class="display-6"><strong>OTHER SCHEDULING OPTIONS, OR RESCHEDULE AN APPOINTMENT: </strong></div>
<div class="mt-4">
<a class = "btn btn-lg btn-outline-dark mx-3" href="tel:3853237118"><i class="fas fa-phone"></i> CALL US AT (385)323-7118</a>
<a class = "btn btn-lg btn-outline-dark mx-3" href="mailto:"><i class="fas fa-envelope"></i> SEND US AN EMAIL</a>
</div>
</div>
</div>
<hr class="my-4">
<div class="text-center"><a class="btn btn-dark" href="/cars">Back to All Cars</a></div>
Ошибка браузера
ValidationError: Appointment validation failed: time: Path `time` is required., date: Path `date` is required., phone: Path `phone` is required., email: Path `email` is required.
at model.Document.invalidate (/Users/Joselito/Desktop/JustCarsFinal/node_modules/mongoose/lib/document.js:2626:32)
at /Users/Joselito/Desktop/JustCarsFinal/node_modules/mongoose/lib/document.js:2446:17
at /Users/Joselito/Desktop/JustCarsFinal/node_modules/mongoose/lib/schematype.js:1225:9
at process._tickCallback (internal/process/next_tick.js:61:11)