Редактировать # 2: Рабочий код
Это делает то, что я хочу сейчас сделать:
// route
app.post("/users/:id/createStudent", function(req, res){
Student.create(function(err){
if(err){
console.log(err)
res.redirect("/")
} else {
const newStudent = new Student({
firstName: req.body.firstName,
lastName: req.body.lastName,
age: req.body.age,
instrument: req.body.instrument,
});
newStudent.save()
.then(() => Parent.findById(req.params.id))
.then((parent) => {
parent.students.push(newStudent);
return parent.save();
});
req.flash("success", "Successfully Created Student");
res.redirect("/users/:id");
}
})
});
// parent model
const mongoose = require("mongoose"),
Schema = mongoose.Schema,
passportLocalMongoose = require("passport-local-mongoose");
const ParentSchema= new Schema({
username: String,
lastName: String,
email: String,
password: String,
students: [],
});
ParentSchema.plugin(passportLocalMongoose);
const Parent = mongoose.model("parent", ParentSchema);
module.exports = Parent;
Новый разработчик здесь. Я пытаюсь создать приложение, в котором родительский пользователь может создать пользователя-ученика, а пользователь-учитель может назначать указанным ученикам еженедельные задачи. У меня проблемы с маршрутом создания студента. Я не уверен, как заставить объект ученика правильно хранить идентификатор родителя. Я пытался найти решение в течение нескольких дней и, похоже, не могу найти ничего, что конкретно связано с этим, и документы тоже не помогли. Надеюсь, мне что-то не хватает, и один из вас, добрые люди, может по крайней мере указать мне правильное направление.
Вот мой код:
//parent model
const mongoose = require("mongoose"),
passportLocalMongoose = require("passport-local-mongoose");
const parentSchema= new mongoose.Schema({
username: String,
lastName: String,
email: String,
password: String,
student: {
id: {
type: mongoose.Schema.Types.ObjectId,
ref: "Student"
},
username: String,
}
});
parentSchema.plugin(passportLocalMongoose);
module.exports = mongoose.model("Parent", parentSchema);
// student model
const mongoose = require("mongoose");
const studentSchema = new mongoose.Schema({
firstName: String,
lastName: String,
age: String,
instrument: String,
parent: {
id: {
type: mongoose.Schema.Types.ObjectId,
ref: "Parent"
},
username: String
},
});
module.exports = mongoose.model("Student", studentSchema);
// create student route
app.post("/users/:id/createStudent", function(req, res){
const newStudent = new Student({
firstName: req.body.firstName,
lastName: req.body.lastName,
age: req.body.age,
instrument: req.body.instrument,
parent: {
_id: {
type: mongoose.Schema.Types.ObjectId,
ref: "Parent"
},
username: String
},
});
Parent.findById(req.params.id, function(err, foundParent){
if(err){
req.flash("error", "Something went wrong");
console.log(err);
res.redirect("/users/:id");
} else {
const parent = foundParent
Student.create(newStudent, parent, function(err, student){
if(err){
console.log(err);
} else {
student.parent.id = req.parent._id;
student.parent.username = req.parent.username;
student.save();
parent.student.push(newStudent);
parent.save();
req.flash("success", "Successfully Created Comment");
res.redirect("/users/" + parent._id);
}
})
}
});
});
В оболочке mon go , db.students.find()
выводит это как объект моего ученика после того, как я заполню форму:
db.students.find()
{ "_id" : ObjectId("5f0b33facd6fa70355f14774"), "firstName" : "Johnny", "lastName" : "Apple", "age" : "2014-03-04", "instrument" : "drums", "parent" : { "username" : "function String() { [native code] }" }, "__v" : 0 }
Извините за длинный код. Я просто пробовал так много вещей, что это добавилось к тому, что вы видите здесь. Спасибо за любой совет, который вы могли бы дать, и за то, что дочитали до этого места. Я полагаю, это потому, что у меня там нет населения. Я просто не уверен, где подойдет вариант заполнения?