猫鼬-无法根据需要设置子文档(嵌套对象)

时间:2018-07-27 13:37:10

标签: node.js mongodb mongoose

我试图将AttendanceSchema的“ day”和“ attenance”键设置为必需,但是没有成功。

如果我在“日”和“出勤”期间都保存了伪造的数据,猫鼬会按预期返回错误。但是,如果我没有一个保存,Mongoose不会返回任何错误并将其保存。

感谢阅读。


这是我的代码。

ClassSchema.js

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

StudentSchema.js

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 } ] }

0 个答案:

没有答案