html 从表单上传字符串数组到MongoDB

ig9co6j1  于 2023-09-28  发布在  Go
关注(0)|答案(1)|浏览(74)

我一直在尝试从HTML表单上传一个字符串数组到我的数据库(MongoDB)。
下面是用于添加类的HTML表单

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Create New Class</title>
</head>
<body>
  <%- include ('./partials/nav') %>
  <h1>Create New Class</h1>
  <form action="/class/add-class" method="post">
    <label for="name">Class Name:</label>
    <input type="text" id="name" name="name" required><br>

    <label for="subjects">Enrolled Subjects:</label>
    <select id="subjects" name="subjects[]" multiple required>
      <% subjects.forEach(function(subject) { %>
        <option value="<%= subject._id %>"><%= subject.name %></option>
      <% }) %>
    </select><br>

    <button type="submit">Submit</button>
  </form>
</body>
</html>

下面是班级路线

const express = require('express');
const router = express.Router();
const Subject = require('../models/course');
const Class = require('../models/class');

router.get('/', async (req, res) => {
    const classes = await Class.find();
    res.render('class', {classes})
});

router.get('/add-class', async (req, res) => {
    const subjects = await Subject.find();
    res.render('addClass', {subjects})
});

router.post('/add-class', (req, res) => {
    const newClass = new Class ({
      name: req.body.name,
      subjects: req.body.subjects,
    });
    Class.create(newClass).then((newlycreated) => {
        req.flash('success', 'Successful');
        res.redirect('/class/add-class');
    })
    .catch((err) => {
            req.flash('error', err.message);
            res.redirect('/class/add-class');
    })
});

module.exports = router;

这就是类模型

const mongoose = require('mongoose');

const classSchema = new mongoose.Schema({
    name: String,
    subjects: [String] // Subjects for this class
  });
  
  const Class = mongoose.model('Class', classSchema);
  
  module.exports = Class;

这是主体模型

const mongoose = require('mongoose');

const subjectSchema = new mongoose.Schema({
    name: String,
    });
  
  const Subject = mongoose.model('Subject', subjectSchema);
  
  module.exports = Subject;

这是主题路线

const express = require('express');
const router = express.Router();
const Subject = require('../models/course')

router.get('/', async (req, res) => {
    const subjects = await Subject.find();
    res.render('courses', {subjects})
});

router.get('/add-subject', async (req, res) => {
    res.render('addCourses')
});

router.post('/add-subject', (req, res) => {
    const newSubject = new Subject ({
        name: req.body.name,
    });
    Subject.create(newSubject).then((newlycreated) => {
        req.flash('success', 'successful');
        res.redirect('/subject/add-subject');
    })
    .catch((err) => {
        req.flash('error', err.message);
        res.redirect('/subject/add-subject');
    })
    })

module.exports = router;

这是我不断得到的输出。

{
  "_id": {
    "$oid": "650c30b86c0f8320412f12ef"
  },
  "name": "SSS 1",
  "subjects": [
    "650b3c26e6e43eca75a4a9fa",
    "650b3cace6e43eca75a4a9fc",
    "650b3cbfe6e43eca75a4a9fe",
    "650b3cc6e6e43eca75a4aa00",
    "650b3cd5e6e43eca75a4aa02",
    "650b3cdde6e43eca75a4aa04",
    "650b3ce8e6e43eca75a4aa06",
    "650b3cefe6e43eca75a4aa08",
    "650b3d25e6e43eca75a4aa0c",
    "650b3d2ce6e43eca75a4aa0e",
    "650b3d68e6e43eca75a4aa18",
    "650b3d74e6e43eca75a4aa1a",
    "650b3dabe6e43eca75a4aa22"
  ],
  "__v": 0
}

我使用了另一个路由,看看我是否可以绕过它,我仍然遇到了一个路障,我也尝试使用.populate()属性,它仍然返回一个空字符串数组

router.get('/:id', async (req, res) => {
  try {
    const classData = await Class.findById(req.params.id).populate('subjects');

    // Iterate over the subjects and replace IDs with names
    const subjectsWithNames = classData.subjects.map(subject => subject.name);

    // Send the response
    res.json({
      _id: classData._id,
      name: classData.name,
      subjects: subjectsWithNames,
      __v: classData.__v
    });
  } catch (error) {
    console.error(error);
    res.status(500).send('Internal Server Error');
  }
});

这是输出

{"_id":"650c30b86c0f8320412f12ef","name":"SSS 1","subjects":[null,null,null,null,null,null,null,null,null,null,null,null,null],"__v":0}
sr4lhrrt

sr4lhrrt1#

在添加类表单中,值是保存到数据库中的值。因此,与<%= subject._id %>不同的是,将其更改为<%= subject.name %>,它将名称而不是ID保存到数据库。原型如下所示

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Create New Class</title>
</head>
<body>
  <%- include ('./partials/nav') %>
  <h1>Create New Class</h1>
  <form action="/class/add-class" method="post">
    <label for="name">Class Name:</label>
    <input type="text" id="name" name="name" required><br>

    <label for="subjects">Enrolled Subjects:</label>
    <select id="subjects" name="subjects[]" multiple required>
      <% subjects.forEach(function(subject) { %>
        <option value="<%= subject.name %>"><%= subject.name %></option>
      <% }) %>
    </select><br>

    <button type="submit">Submit</button>
  </form>
</body>
</html>

相关问题