我正在创建一个简单的节点表达应用程序,我正在制作注册功能。我从我的索引路由调用createUser,它在我的用户模型中调用该函数,然后密码被加密和存储。但是当它从索引路由调用createUser函数时,它会给出上述错误。我无法弄清楚问题是什么!!
这是我的索引路径文件
var express = require('express');
var router = express.Router();
var User = require('../models/User.js');
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
router.post('/login', function(req, res, next){
var username = req.body.username;
var password = req.body.password;
User.getUserByUsername(username, function(err, user){
if(err) throw err;
if(!user){
return res.send({msg: 'no user was found with this username'});
}
User.checkPassword(user, password, function(err, result){
if (err) {
throw err;
return null;
}
if(user){
res.send({msg:'You are now logged in'});
}else{
res.send({msg: 'Your password is wrong'});
}
})
});
});
router.post('/signup', function(req, res, next){
var username = req.body.username;
var password = req.body.password;
var password2 = req.body.password2;
console.log(req.body);
req.checkBody('username', 'username field is required').notEmpty();
req.checkBody('password', 'password field is required').notEmpty();
req.checkBody('password2', 'confirm password field is required').notEmpty();
var errors = req.validationErrors();
console.log(errors);
if(errors){
req.flash('error', 'there was some error with the signup process');
res.send('there was some validation error');
}else{
var newUser = new User({
username: username,
password:password
});
console.log(newUser);
User.createUser(newUser, function(err, user){
if (err) throw err;
console.log(user);
res.send('user was created');
})
}
});
module.exports = router;
这是我的模型和架构
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/quizapp');
var db = mongoose.connection;
var bcrypt = require('bcrypt');
var UserSchema = mongoose.Schema({
username:{
type:String,
required: true
},
password:{
type:String,
required:true,
bcrypt:true
}
});
module.exports.getUserByUsername = function(username, callback){
User.findOne({username:username}, callback);
}
module.exports.checkPassword = function(pass, callback){
callback(null, true);
}
module.exports.createUser = function (newUser, callback) {
bcrypt.hash(newUser.password, 10, function(err, hash){
if(err) throw err;
newUser.password = hash;
User.save(newUser, callback);
});
};
var User = module.exports = mongoose.model('User',UserSchema);
答案 0 :(得分:0)
首先,使用
将函数createUser
附加到module.exports
module.exports.createUser = function (newUser, callback) {
bcrypt.hash(newUser.password, 10, function(err, hash){
if(err) throw err;
newUser.password = hash;
User.save(newUser, callback);
});
};
然后你用
覆盖module.exportsvar User = module.exports = mongoose.model('User',UserSchema);
所以现在module.exports
只包含最后一次分配的值。
尝试这样做,
var User = mongoose.model('User',UserSchema);
module.exports.User = User;