TypeError:无法读取属性' q1'未定义的

时间:2018-05-09 14:25:13

标签: node.js mongoose mongoose-schema

我设计了我的mongoose架构,其中包含了对象内部组合。这是User.js:

var mongoose = require("mongoose");
var Schema = mongoose.Schema;

var UserSchema = new Schema({
   name:String,
   surname:String,
   questions: {
    q1:{statement:String, spoof:Boolean},
    q2:{statement:String, spoof:Boolean},
    q3:{statement:String, spoof:Boolean}
 },
 color:{
   red:Number,
   green:Number,
   blue:Number
 }
});

var User = mongoose.model("User", UserSchema);
module.exports = User;`

所以我想要三个问题然后三个数字似乎很好。 但是,当我需要这个模式并引用User.questions时它表示它是未定义的,即使我已在模式中定义它? 这是我从表单处理POST数据并尝试将其保存到DB

的地方
app.post("/register", (req, res) => {

   User.firstname = req.body.firstname;
   User.surname = req.body.surname;
   User.questions.q1.statement = req.body.q1;
   User.questions.q1.spoof = strToBoolean(req.body.q1Spoof);
   User.questions.q2.statement = req.body.q2;
   User.questions.q2.spoof = strToBoolean(req.body.q2Spoof);
   User.questions.q3.statement = req.body.q3;
   User.questions.q3.spoof = strToBoolean(req.body.q3Spoof);
   User.color.red = 255;
   User.color.green = 255;
   User.color.blue = 255;
   User.save(err => console.log("Did not save to database: \n" + err));

});

strToBoolean函数将字符串转换为布尔值 这应该是直截了当的?但我还没有看到任何能帮助我的答案。任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:0)

User是一个模型。您需要基于此模型实例化文档并将变量分配给:

app.post("/register", (req, res) => {

   let user = new User()
   user.firstname = req.body.firstname;
   user.surname = req.body.surname;
   user.questions.q1.statement = req.body.q1;
   user.questions.q1.spoof = strToBoolean(req.body.q1Spoof);
   user.questions.q2.statement = req.body.q2;
   user.questions.q2.spoof = strToBoolean(req.body.q2Spoof);
   user.questions.q3.statement = req.body.q3;
   user.questions.q3.spoof = strToBoolean(req.body.q3Spoof);
   user.color.red = 255;
   user.color.green = 255;
   user.color.blue = 255;
   user.save(err => console.log("Did not save to database: \n" + err));

});

我不确定当没有默认值时,Mongoose如何处理嵌套对象模式,因此您可能需要先实例化问题对象以及q1q2q3中的每一个也可以分配给他们:

   user.questions = {q1: {}, q2: {}, q3: {}};
   user.questions.q1.statement = req.body.q1;

您还可以通过将对象传递给构造函数来创建文档:

   let user = new User({
     firstname: req.body.firstname,
     surname: req.body.surname,
     questions: {
      q1: {
        statement: req.body.q1,
        spoof: strToBoolean(req.body.q1Spoof)
      },
      q2: {
        statement: req.body.q2,
        spoof: strToBoolean(req.body.q2Spoof)
      },
      q3: {
        statement: req.body.q3,
        spoof: strToBoolean(req.body.q3Spoof)
      }
    }
    color: {
      red: 255,
      green: 255,
      blue: 255
    }
   })
   user.save(err => console.log("Did not save to database: \n" + err));