Node.js无法记录Student模型中的类模型数据

时间:2017-07-30 04:34:51

标签: javascript node.js mongoose

我在这里遇到问题。我目前正在使用node.js和MongoDB创建一个学校目录。我在app.post请求中,由于某种原因,我无法获取链接到学生的类的名称以登录到控制台,但createdClass.name将打印...

这是代码......

app.post("/students/:id", function(req, res){
   Student.findById(req.params.id, function(err, foundStudent){
       if(err){
           console.log(err);
       } else {
          Class.create(req.body.class, function(err, createdClass){
              if(err){
                  console.log(err);
              } else {
                  createdClass.student.id = foundStudent._id;
                  createdClass.student.name = foundStudent.name;
                  console.log(createdClass);
                  createdClass.save();

                  foundStudent.classes.push(createdClass);
                  console.log(foundStudent.classes[0].name);
                  foundStudent.save();
              }
          });
       }
   });
   res.redirect("/students/" + req.params.id);
});

另外,这是我的模特......

STUDENT:

var mongoose = require("mongoose");

var studentSchema = new mongoose.Schema (
    {
        name: String,
        classes: [
                {
                    type: mongoose.Schema.Types.ObjectId,
                    ref: "Class"
                }
            ],
        grades: Array
    }
);

module.exports = mongoose.model("Student", studentSchema);

CLASS:

var mongoose = require("mongoose");

var classSchema = new mongoose.Schema (
    {
        name: String,
        student: 
        {
            id: 
            {
                type: mongoose.Schema.Types.ObjectId,
                ref: "Student"
            },
            name: String
        }
    }
);

module.exports = mongoose.model("Class", classSchema);

提前感谢您,如果有任何我可以添加的内容,请告诉我,以便更容易阅读。

以下是发布帖子请求的页面...

<div>
    <h1>Student Profile</h1>
    <h2>Name: <%=student.name%></h2>
    <div>
        <h3>Classes:
            <form action="/students/<%= student._id %>" method="POST">
                <%if(student.classes.length === 0){%>
                    <p>No classes linked to profile, please add class..</p>
                    <input type="text" name="class[name]" placeholder="Class name">
                <% } else { %>
                    <% student.classes.forEach(function(course){ %>
                        <li><%= course.name %></li>
                    <% }); %>
                <% } %>
            </form>
        </h3>
    </div>
</div>

1 个答案:

答案 0 :(得分:1)

Class是保留字,不能用于变量