【发布时间】:2018-01-06 09:51:40
【问题描述】:
我无法从另一个对象中获取要记录的引用数据。
我目前有两个模型...
var mongoose = require("mongoose");
学生:
var gameSchema = new mongoose.Schema(
{
name: String,
courses: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "Course"
}
]
});
module.exports = mongoose.model("Student", gameSchema);
课程:
var mongoose = require("mongoose");
var courseSchema = new mongoose.Schema (
{
name: String,
student: [
{
id:
{
type: mongoose.Schema.Types.ObjectId,
ref: "Student"
},
name: String
}
]
}
);
module.exports = mongoose.model("Course", courseSchema);
当我 console.log(foundStudent.courses[0].name) 时,我得到了未定义,我不知道为什么......
app.post("/students/:id", function(req, res){
Student.findById(req.params.id, function(err, foundStudent){
if(err){
console.log(err);
} else {
Course.create(req.body.class, function(err, createdCourse){
if(err){
console.log(err);
} else {
createdCourse.student.push(foundStudent);
createdCourse.save();
foundStudent.courses.push(createdCourse);
foundStudent.save();
res.redirect("/students/" + req.params.id);
}
});
}
});
});
这里是展示页面...
<div>
<h1>Student Profile</h1>
<h2>Name: <%=student.name%></h2>
<div>
<h3>Classes:
<form action="/students/<%= student._id %>" method="POST">
<% student.courses.forEach(function(course){ %>
<li><p><%= course.name %></p></li>
<% }); %>
<a href="/students/<%=student._id%>/courses/new">Add Course</a>
</form>
</h3>
</div>
</div>
【问题讨论】:
-
您必须使用populate 自动获取引用的对象。
-
这应该进入 get 路线是吗?
-
是的,在任何返回
DocumentQuery对象的 find 方法之后。这意味着回调必须移动到 DocumentQuery 对象的exec方法,例如:Student.findById(id).populate('courses').exec((err, res) => ...)。 -
遗憾的是,这仍然只保留 id 而不是我的 Student 对象中的值。
app.get("/students/:id", function(req, res){ Student.findById(req.params.id).populate("courses").exec(function(err, foundStudent){ if(err){ console.log(err); } else { console.log(foundStudent); res.render("students/show", {student: foundStudent}); } }); }); -
我添加了一个示例作为对您主题的回答。解释如何在 SO 注释中正确使用填充占用了太多字符。
标签: javascript node.js