我有以下用户架构:
var mongoose = require('mongoose');
var userSchema = mongoose.Schema({
local: {
email: String,
password: String
},
education: {
school: {
start: Boolean,
name: String,
graduationYear: String
},
college: {
start: Boolean,
name: String,
career: String,
enterYear: String,
graduationYear: String
}
}
});
现在,当我提交包含所有这些信息的表单时,我的应用会将POST请求路由到以下功能:
exports.postEditEducation = function (req, res){
process.nextTick(function (){
var user = req.user;
user.education.school.start = req.body.schoolStart;
user.education.school.name = req.body.schoolName;
user.education.school.graduationYear = req.body.graduationYear;
user.education.college.start = req.body.collegeStart;
user.education.college.name = req.body.collegeName;
user.education.college.career = req.body.collegeCareer;
user.education.college.enterYear = req.body.collegeEnterYear;
user.education.college.graduationYear = req.body.collegeGraduationYear;
user.save(function (err){
if (err)
throw err;
res.redirect('/profile');
});
});
};
但是,当我提交信息时,出现以下错误:
user.education.college.start = req.body.collegeStart;
^
TypeError: Cannot set property 'start' of undefined
at /file.js:464:46
at process._tickCallback (node.js:419:13)
最佳答案
var user = req.user;
您已经为保存req.user创建了变量
user.education.college.start
为此,您应该创建一个用户集合实例。为用户方案创建一些实例。
例如,我假设userschema的集合名称为usercollection:
var userobj = new usercollection();
userobj.education.college.start = req.body.schoolStart; ..
希望这可能有用。
关于node.js - Mongoose 无法读取具有复杂模式的undefined属性,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33311075/