javascript - 将现有项目推送到新创建项目的嵌套数组中

标签 javascript arrays express mongoose ejs

这是我的表格

<form action="/test" method="post">
<input type="text" name="name" id="">
    <input type="text" name="year" id="">
    <!-- This will let me select students from my database in new club by clicking on their checkbox -->
    <% students.forEach((student) => {%>
            <label for="student"><%=character.name%></label>
            <input type="checkbox" name="student" value="<%=student.roll%>">
        <%  }) %> 
    <button type="submit">Submit</button>
</form>

我的 Mongoose 架构

const studentSchema = new mongoose.Schema({
  roll: String,
  reg: String
})


const clubSchema = new mongoose.Schema({
  name: String,
  year: String,
  members: [studentSchema]
})

我的app.js

app.get("/test",(req,res) => {
  Student.find({},(err,foundStudents) => {
    if(!err){
      res.render("test",{students: foundStudents})
    }
  })
    
})
app.post("/test",(req,res) => {
 const newClub = new Club ({
     name: req.body.name,
     year: req.body.year
  })

newClub.save()
})

现在我的问题是,在数据库中注册新俱乐部时,如何将从表单中选择的学生添加到我的 ClubSchema 的成员数组中?

提前致谢,我是编码新手,这是我刚刚玩过的东西。如果以上任何内容您不清楚,请在评论中询问我,这是我第一次在线寻求帮助,所以可能会有一些错误。

最佳答案

当你需要在集合之间建立关系时,你应该使用引用,你不应该复制整个文档,因为数据会重复。

test.ejs:

<form action="/test" method="post">
  <label>Club Name:</label>
  <input type="text" name="name" id="" />
  <br />
  <label>Year:</label>
  <input type="text" name="year" id="" />
  <br />
  <label>Members:</label>
  <br />
  <% students.forEach((student, index) => {%>
  <input
    type="checkbox"
    name="students"
    id="<%=index%>"
    value="<%=student._id%>"
  />
  <label for="<%=index%>"><%=student.name%></label>
  <% }) %>
  <br />
  <button type="submit">Submit</button>
  <br />
  <a href="/clubs">List Clubs</a>
</form>

Models.js:

const mongoose = require("mongoose");
mongoose.connect("mongodb://docker:mongopw@localhost:49153");

const studentSchema = new mongoose.Schema({
  name: String,
  reg: String,
});

const clubSchema = new mongoose.Schema({
  name: String,
  year: String,
  members: [{ type: mongoose.Schema.Types.ObjectId, ref: "Student" }],
});

let Student = new mongoose.model("Student", studentSchema);
let Club = new mongoose.model("Club", clubSchema);

(async function SeedDataBase() {
  let students = await Student.find();
  if (students.length === 0) {
    new Student({ name: "Paul", reg: "33735" }).save();
    new Student({ name: "Robert", reg: "48435" }).save();
    new Student({ name: "Mary", reg: "83765" }).save();
    new Student({ name: "Levandowisk", reg: "09555" }).save();
  }
})();

module.exports = { Student, Club };

clubs.ejs:

<a href="/test">Add Club</a>

<div>
  <%clubs.forEach((club) => {%>

  <label>Club Name: </label>
  <label><%=club.name%></label>
  <br />

  <label>Year: </label>
  <label><%=club.year%></label>
  <br />
  <label>Members:</label>
  <br />
  <%club.members.forEach((member) => {%>

  <label>Student Name: </label>
  <label><%=member.name%></label>
  <br />

  <% }) %>

  <br />

  <% }) %>
</div>

App.js:

const express = require("express");
const app = express();
const port = 3000;

const { Student, Club } = require("./Models");

app.set("view engine", "ejs");
app.use(express.urlencoded());

app.get("/test", (req, res) => {
  Student.find({}, (err, students) => {
    if (!err) {
      res.render("test", { students });
    }
  });
});

app.post("/test", (req, res) => {
  new Club({
    name: req.body.name,
    year: req.body.year,
    members: req.body.students,
  })
    .save()
    .then(() => {
      res.redirect("/clubs");
    });
});

app.get("/clubs", (req, res) => {
  Club.find()
    .populate("members")
    .then((clubs, err) => {
      if (!err) {
        res.render("clubs", { clubs });
      }
    });
});

app.listen(port);

关于javascript - 将现有项目推送到新创建项目的嵌套数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72903212/

相关文章:

javascript - 使用精确参数调用的 Sinon js 检查 stub

javascript - 获取货币符号 Angular 2

javascript - 绘制到第二个 Canvas 会取消第一个 Canvas

javascript - 如何在 Meteor + Ionic 应用程序中使用 Meteor 方法

javascript - 以 Angular 访问全局变量

node.js - express.js 未在 NodeUnit 测试中保存 session 数据

java - 如何在java中自动填充数组?

c - 将文件中的值读取到不对应的数组中

java - java中的可变字节数组

mysql - Nodejs Sequelize 和passport Js,在注册用户时卡在执行查询上