我试图将AttendanceSchema的“ day”和“ attenance”键设置为必需,但是没有成功。
如果我在“日”和“出勤”期间都保存了伪造的数据,猫鼬会按预期返回错误。但是,如果我没有一个保存,Mongoose不会返回任何错误并将其保存。
感谢阅读。
import mongoose from "mongoose"
const ClassSchema = new mongoose.Schema({
className: {type: String, required: true},
classTeacher: {type: String, required: true},
studentName: {type: mongoose.Schema.Types.String, ref: 'Student', required: true}, //This required works.
attendance: {type: mongoose.Schema.Types.String, ref: 'Student', required: true} //This required works.
})
const Classroom = mongoose.model("Class", ClassSchema)
export default Classroom
import mongoose from "mongoose"
const AttendanceSchema = new mongoose.Schema({
day: {type: String, required:true}, //This required doesn't work.
attendance: {type: Boolean, required:true} //This required doesn't work.
})
const StudentsSchema = new mongoose.Schema({
studentName: String,
attendance: AttendanceSchema //I set this "attendance" as required, but it didn't change anything, so I left the required out.
})
const Student = mongoose.model("Student", StudentsSchema)
export default Student
const fakeClassroom = {
className: "How to be a Super-Hero",
classTeacher: "Spider-Man",
studentName: "Ant-Man",
attendance: [
/* {day: "monday"}, */ //Commented out to test if it's required
{attendance: true}
]
}
exports.postClassroom = (req, res)=>{
const newClass = new Classroom (req.body)
newClass.save((err)=>{
console.log(req.body)
if(err){
if (err.name == "ValidationError"){
return res.status(400).json({message:"Class Name and Class Teacher are required"})
} else {
return res.status(500).json({message:"Error creating classroom"})}
}
res.status(200).json({message: "Class created successfully"})
})
}
{ className: 'How to be a Super-Hero',
classTeacher: 'Spider-Man',
studentName: 'Ant-Man',
attendance: [ { attendance: true } ] }