2016-05-17 31 views
0

How can I solve this error TypeError: Users is not a function我怎样才能解决这个错误类型错误:用户不是一个函数

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; 

Im trying to insert a new user into my mongodb, but I keep getting an error that User is not a function, I have my above code is in my routes folder and the below code is my schema

 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

嗨Mlindos。你从哪里得到错误?您在很多地方都有参考用户 – codeshinobi

回答

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) 
相关问题