#node.js #mongodb #express #ejs
Вопрос:
Это мой файл схемы: с именем form.js
const mongoose = require('mongoose');
const UploadedFile = new mongoose.Schema({
path: String,
type: String,
size: Number,
folder: String,
filename: String
})
const Form = mongoose.model('Form', {
lname:{
type:String,
required:true
},
fname:{
type:String,
required:true
},
email: {
type: String,
required: true },
country:{
type:String,
required:true
},
visa:{
type:String,
required:true
},
undergraduate:{
type:String,
required:true
},
semester:{
type:String,
required:true
},
year:{
type:Number,
required:true
},
gender:{
type:String,
required:true
},
Degree_Con:{
type:String,
required:true
},
gpa:{
type:Number,
required:true
},
status:{
type:String,
required:true
},
uploadedFile: UploadedFile
});
module.exports = Form;
==================================================================================
Это мой файл маршрутизатора с именем forms.js
//Libraries
const express = require('express');
const router = express.Router();
const mongoose = require("mongoose");
const Grid = require('gridfs-stream');
const util = require("util");
const multer = require("multer");
const GridFsStorage = require("multer-gridfs-storage");
const path = require('path');
const crypto = require('crypto');
//User Form mode
const User = require('../model/form');
const mongoURI = "mongodb://localhost:27017/Mongocon";
// // Init gfs
let gfs;
const conn = mongoose.connection;
conn.on('error', console.log.bind(console, "connection error"));
conn.once('open', () => {
// Init stream
gfs = Grid(conn.db, mongoose.mongo);
gfs.collection('uploads');
});
// Create storage engine
const storage = new GridFsStorage({
url: mongoURI,
file: (req, file) => {
return new Promise((resolve, reject) => {
crypto.randomBytes(16, (err, buf) => {
if (err) {
return reject(err);
}
const filename = buf.toString('hex') path.extname(file.originalname);
const fileInfo = {
filename: filename,
bucketName: 'Form'
};
resolve(fileInfo);
});
});
}
});
const Form = multer({ storage });
router.get('/dashboard', (req, res) => {
gfs.files.find().toArray((err, files) => {
// Check if files
if (!files || files.length === 0) {
res.render('dashboard', { files: false });
} else {
files.map(file => {
if (
file.contentType === 'image/jpeg' ||
file.contentType === 'image/png'
) {
file.isImage = true;
} else {
file.isImage = false;
}
});
res.render('dashboard', {files: files });
}
});
});
//Dashboard Handle
router.post('/dashboard', Form.single('file'), (req,res)=> {
const{ lname ,fname, email,country,visa,undergraduate,semester,year,gender,Degree_Con,gpa,status,uploadedFile } = req.body;
let errors = [];
//check required fields
if(!lname || !fname ||!email || !country || !visa || !undergraduate ||!semester || !year || !gender || !Degree_Con || !gpa || !status || !uploadedFile)
{
errors.push({msg: 'Please fill in all fields'});
}
if(errors.length > 0)
{
res.render('dashboard',{
errors,
lname,
fname,
email,
country,
visa,
undergraduate,
semester,
year,
gender,
Degree_Con,
gpa,
status,
uploadedFile
});
}
else
{
const newForm = new Form({ lname ,fname, email,country,visa,undergraduate,semester,year
,gender,Degree_Con,gpa,status,uploadedFile });
newForm.save();
res.redirect('/dashboard');
}
});
module.exports = router;
==============================================================================
приборная панель.ejs
<h1 class="mt-8">Dashboard</h1>
<hr>
<div class="row mt-5">
<div class="col-md-6 m-auto">
<div class="card card-body">
<h1 class="text-center mb-3">
<i class="fas fa-user-plus"></i>Applicant Form
</h1>
<%- include ("./partials/messages"); %>
<form action="/forms/dashboard" method="POST" enctype="multipart/form-data">
<div class="form-group">
<label for="lname">Last Name</label>
<input
type="name"
id="lname"
name="lname"
class="form-control"
placeholder="Enter LastName"
/>
<div class="form-group">
<label for="fname">First Name</label>
<input
type="name"
id="fname"
name="fname"
class="form-control"
placeholder="Enter FirstName"
/>
</div>
</div>
<div class="form-group">
<label for="email">Email</label>
<input
type="email"
id="email"
name="email"
class="form-control"
placeholder="Enter Email"
/>
</div>
<div class="form-group">
<label for="country">Country</label>
<select class="selectpicker countrypicker"
data-live-search="true"
data-default="United States"
data-flag="true">
</select>
</div>
<div class="form-group">
<label for="visa">Visa Status</label>
<input class="form-control" type="text" value="" id="visa">
</div>
<div class="form-group">
<label for="Undergraduate">Undergraduate Degree</label>
<input class="form-control" type="text" value="" id="Undergraduate">
</div>
<div class="form-group">
<label for="sem">Semester</label>
<input class="form-control" type="text" value="Spring/Fall" id="sem">
</div>
<div class="form-group">
<label for="sem">Year</label>
<input class="form-control" type="number" placeholder="2021" id="sem">
</div>
<fieldset class="form-group">
<label for="example-date-input" >Gender:</label>
<div class="form-check">
<label class="form-check-label">
<input type="radio" class="form-check-input" name="optionsRadios" id="optionsRadios1" value="Female" checked>
Female
</label>
</div>
<div class="form-check">
<label class="form-check-label">
<input type="radio" class="form-check-input" name="optionsRadios" id="optionsRadios2" value="Male" checked>
Male
</label>
</div>
</fieldset>
<div class="form-group">
<button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Degree Concentrations
</button>
<div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
<a class="dropdown-item" href="#">Web and Databases</a>
<a class="dropdown-item" href="#">Artificial Intelligence</a>
<a class="dropdown-item" href="#">Cyber Security</a>
</div>
</div>
<div class="form-group">
<label for="example-text-input">GPA</label>
<input class="form-control" type="number" value="4" id="example-text-input">
</div>
<div class="custom-file mb-3">
<input type="file" name="file" id="file" class="custom-file-input">
<label for="file" class="custom-file-label">Upload Transcription in pdf or docx form</label>
</div>
<fieldset class="form-group">
<label for="example-date-input" >Status</label>
<div class="form-check">
<label class="form-check-label">
<input type="radio" class="form-check-input" name="Statusopt" id="Status1" value="Accept" checked>
Accept
</label>
</div>
<div class="form-check">
<label class="form-check-label">
<input type="radio" class="form-check-input" name="Statusopt" id="Status2" value="Reject" checked>
Reject
</label>
</div>
<div class="form-check">
<label class="form-check-label">
<input type="radio" class="form-check-input" name="Statusopt" id="Status3" value="Defer" checked>
Defer
</label>
</div>
</fieldset>
<input type="submit" value="Submit" class="btn btn-primary btn-block">
</form>
</div>
</div>
</div>
<hr>
<a href="/users/logout" class="btn btn-secondary">Logout</a>
=========================================================
Проблема, с которой я сталкиваюсь с кодом, заключается в том, что мой файл загружается, но не другие поля ввода в базу данных, более того, я понятия не имею о том, как сохранить переключатель и раскрывающийся список в MongoDB, я очень новичок в node js и MongoDB, поэтому мне становится все труднее разобраться в этом, я искал в Интернете те же проблемы уже 2 недели, но нет ничего, что могло бы решить мою проблему, я надеюсь получить здесь несколько советов