无法设置未定义的属性“名称”

时间:2018-02-21 13:00:36

标签: node.js mongodb mongoose-schema

const mongoose = require('mongoose');

let All = mongoose.Schema({
  school:{
      name:{
        type: String,
      },
      program:[{
        name: String,
        semester: Number,
        subject: [{name: String, crh: Number}]
      }]
  }
})

let allSub = module.exports = mongoose.model('allSub', All);

我创建的猫鼬收藏

if(!course){
      let x = new All();
      x.school.name = School;
      x.school.program.name = Course;
      x.school.program.semester = Semester;
      x.school.program.subject.name = "One";
      x.save((err) =>{
        if(err) throw err;
        console.log("Date saved");
        res.render('addinsub');
      })
    }

数据插入块。它给了我一个错误,说明未定义的x.school.program.subject.name。 如何克服这个错误?

2 个答案:

答案 0 :(得分:0)

您需要先创建对象。

const x = new All();
x.school = {
    name: Course,
    program: [{
        semester: Semester,
        subject: {
            name: "one"
        }
    }]
};
x.save((err) => {
    if (err) throw err;
    console.log("Date saved");
    res.render('addinsub');
})

答案 1 :(得分:0)

您需要x.school.program.subject作为对象。

if(!course){
  let x = new All();
  x.school.name = School;
  x.school.program.name = Course;
  x.school.program.semester = Semester;
  x.school.program.subject = {name: "One"};
  x.save((err) =>{
    if(err) throw err;
    console.log("Date saved");
    res.render('addinsub');
  })
}