如何解决此错误TypeError:用户不是函数
var express = require('express');
var router = express.Router();
var Users = require('../models/user');
router.post('/signup', function(req, res){
// res.send('Ok');
var name = req.body.name;
var surname = req.body.surname;
var email = req.body.email;
var username = req.body.username;
var password = req.body.password;
var confirm_password = req.body.confirm_password;
req.checkBody('name', 'Name is required').notEmpty();
req.checkBody('surname', 'Surname is required').notEmpty();
req.checkBody('email', 'Email address is required').notEmpty();
req.checkBody('email', 'Invalid email address').isEmail();
req.checkBody('username', 'Username is required').notEmpty();
req.checkBody('password', 'Password is required').notEmpty();
req.checkBody('confirm_password', 'Passwords do not match').equals(req.body.password);
var errors = req.validationErrors();
if(errors){
res.json({status: errors})
}else{
var newUser = new Users({
name:name,
surname:surname,
email:email,
username:username,
password:password
})
Users.createUser(newUser, function(err, user){
if(err){ throw err};
console.log(user);
});
res.json({status:"success"})
}
})
router.get('/signin', function(req, res){
res.send('Sure');
})
module.exports = router;
我试图将一个新用户插入到我的mongodb中,但我一直收到一个错误,即User不是一个函数,我的上面的代码在我的routes文件夹中,下面的代码是我的架构
var mongoose = require('mongoose')
var Schema = mongoose.Schema;
var bcrypt = require('bcryptjs');
var usersSchema = new Schema({
name:{
type:String,
required:true
},
surname:{
type:String,
required:true
},
email:{
type:Number
},
username:{
type:Number
},
password:{
type:Number
},
create_date:{
type:Date,
default:Date.now
}
})
var Users = mongoose.model('Users', usersSchema);
module.exports.createUser = function(newUser, callback){
// hashing the passwords
bcrypt.genSalt(10, function(err, salt){
bcrypt.hash(newUser.password, salt, function(err, hash){
newUser.password = hash;
newUser.save(callback);
})
})
}
答案 0 :(得分:2)
您必须导出用户模型。 阅读mongoose guide
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var bcrypt = require('bcryptjs');
var usersSchema = new Schema({
name: {
type: String,
required: true
},
...
})
usersSchema.statics.createUser = function (newUser, callback) {
...
}
module.exports = mongoose.model('Users', usersSchema)