我正在使用nodejs进行测试注册,我设置了一个免费的mongo实验室数据库,并在我的本地服务器上测试注册。我一直在我的路线上得到这个错误,我可以控制到var user = new User(); (控制台用户)并获取对象。我可以控制user.profile和console将显示名称和图片作为对象等但由于某种原因,我的代码是说user.profile.name是未定义的。你们发现的任何错误?
这是我的模特
var mongoose = require('mongoose');
var bcrypt = require('bcrypt-nodejs');
var Schema = mongoose.Schema;
var UsersSchema = new Schema({
email: {
type: String,
unique: true,
lowercase: true
},
password: String,
profile: {
name: { type: String, default: '' },
picture: { type: String, default: '' }
},
address: String,
history: [{
date: Date,
paid: { type: Number, default: 0 },
}]
});
UsersSchema.pre('save',function(next){
var user = this;
if(!user.isModified('password')) return next();
bcrypt.genSalt(10, function(err, salt){
if(err) return next(err);
bcrypt.hash(user.password,salt, null,function(err,hash){
if (err) return next(err);
user.password = hash;
next();
});
})
})
UsersSchema.methods.comparePassword = function(password){
return bcrypt.compareSync(password, this.password)
}
module.exports = mongoose.model('User',UsersSchema);
这是我的路线文件
var router = require('express').Router();
var User = require('../models/users');
// var user = new User();
// console.log('user',user.profile.name);
router.post('/signup', function(req, res, next) {
var user = new User();
user.profile.name = req.body.name;
user.email = req.body.email;
user.password = req.body.password;
User.findOne({ email: req.body.email }, function(err, existingUser) {
if (existingUser) {
return res.redirect('/signup');
} else {
user.save(function(err, user) {
if (err) return next(err);
res.json("New user has been created");
});
}
});
});
module.exports = router;
//res.json("New user has been created")
答案 0 :(得分:3)
您必须先定义配置文件,因为用户已定义但user.profile不是
在行user.profile = ''
user.profile.name = req.body.name
或替换以下内容并尝试
带有-var User = require('../models/users');
的 var UsersSchema = require('../models/users');
- var user = new User();
与var user = new UsersSchema();
答案 1 :(得分:2)
您正尝试从name
访问profile
属性,该属性未定义。
var user = new User();
user.profile.name = req.body.name;
-----------/\
要完成这项工作,请先定义profile
:
var user = new User();
user.profile = {};
user.profile.name = req.body.name;