2016-04-14 12 views
0

IIユーザーモデルを作成し、それをusers.jsルートファイルで使用したいのですが、userModelは関数です。誰でもここで起こっていることを知っていますか?モデル/ user.jsのモデルを使用してインスタンスを作成すると、 '関数ではありません'(ノードをmongooseで表示)

var mongoose = require('mongoose'); 
var bcrypt = require('bcrypt-nodejs'); 

var url = 'mongodb://fr:[email protected]:13250/node'; 
mongoose.connect(url); 

var db = mongoose.connection; 


db.on('error', console.error.bind(console, 'connection error:')); 

db.once('open', function() {//when connected 
     console.log('connected to mongo db'); 
     //User Schema 
     var UserSchema = mongoose.Schema({ 
      username: { 
       type:String, 
       index:true 
      }, 
      email: { 
       type:String 
      }, 
      password: { 
       type:String, 
       required:true, 
       bcrypt:true 

      }, 
      profileimage: { 
       type:String 
      } 
     }, { timestamps: 'created_at' }); 

     //add "speak" functionality to our documents: 
     UserSchema.methods.speak = function(){ 
      var greeting = this.name 
       ? "His name is " + this.name 
       : "I do not have a nanme"; 
      console.log(greeting); 
     }  

     module.exports = { 
      userModel: mongoose.model('User',UserSchema), 
      createUser: function(newUser,callback){ 
       bcrypt.hash(newUser.password, null, null, function(err, hash) { 
        // Store hash in your password DB. 
        newUser.password = hash; 
        newUser.save(callback); 

       }); 

      } 
     };    
}); 

//routes/users.js

const User = require('../modules/user'); 

    var userModel = User.userModel; 
    var newUser = new userModel({ 
     username:username, 
     email:email, 
     password:password, 
     profileimage: profileImageName 
    }); 

    //Create User 
    User.createUser(newUser,function(err,user){ 
     if(err){throw err} 
     console.log(user); 
    }); 

のおかげで

//私のユーザモデルが追加されます。ルート/ユーザーに関する //より多くを。 js

"use strict"; 
const express = require('express'); 
const router = express.Router(); 

const multer = require('multer'); 

const upload = multer({ dest: '/uploads' }); 

const User = require('../modules/user'); 
//this User returns: 1,User = mongoose.model('User',UserSchema) 
//2: User.createUser = function(newUser,callback){ 
     // newUser.save(callback); 
     // }  

/* GET users listing. */ 
router.get('/', function(req, res, next) { 
    res.send('respond with a resource'); 
}); 

router.get('/register', function(req, res, next) { 
    res.render('register',{ 
     'title': 'Register', 
     'errors':[] 
    }); 
}); 
router.post('/register',upload.single('profileimage'), function(req, res, next) { 
    var username = req.body.username; 
    var email = req.body.email; 
    var password = req.body.password; 
    var password2 = req.body.password2; 

    console.log(username,email,password,password2); 
    //check for image field 
    if(req.file){ 
     console.log('uploading file...'); 

     //file info 
     var profileImageOriginalName = req.file.originalname;//the name before uploaded 
     var profileImageName = req.file.filename;//name the server give it when it uploaded 

     var profileImageMime = req.file.mimetype; 
     var profileImagePath = req.file.path; 
     var profileImageSize = req.file.size; 
    }else{ 
     //set a default image 
     profileImageName = 'noimage.png'; 
    } 
    //form validation, using express-validator 
req.checkBody({ 
'email': { 
    notEmpty: true, 
    isEmail: { 
     errorMessage: 'Invalid Email' 
    } 
    }, 
    'password': { 
    notEmpty: true, 
    isLength: { 
     options: [{ min: 4, max:20 }], 
     errorMessage: 'Password Must be between 4 and 8 chars long' // Error message for the validator, takes precedent over parameter message 
    }, 
    errorMessage: 'Invalid Password' // Error message for the parameter 
    }, 
    'password2': { 
    notEmpty: true, 
    matches: { 
     options: [password, 'g'] // pass options to the validator with the options property as an array 
     // options: [/example/i] // matches also accepts the full expression in the first parameter 
    }, 
    errorMessage: 'Password Not Match' // Error message for the parameter 
    }, 
    'username': { // 
    //optional: true, // won't validate if field is empty 
    notEmpty: true, 
    isLength: { 
     options: [{ min: 4, max: 50 }], 
     errorMessage: 'Username Must be between 4 and 8 chars long' // Error message for the validator, takes precedent over parameter message 
    },  
    errorMessage: 'Invalid Name' 
    } 
}); 



    // req.checkBody('username','userName field is required').notEmpty(); 

    // req.checkBody('email','Email field not valid').isEmail(); 
    // req.checkBody('password','Password field is required').notEmpty(); 
    // req.checkBody('password2','Password do not match').equals(req.body.password); 

    //check for errors 
    var errors = req.validationErrors(); 
    //or let errors = req.asyncValidationErrors(); 
    //errors is like below: 
    //[ 
    // {param: "email", msg: "required", value: "<received input>"}, 
    // {param: "email", msg: "valid email required", value: "<received input>"}, 
    // {param: "password", msg: "6 to 20 characters required", value: "<received input>"} 
    // ] 

    if(errors){ 
     res.render('register',{ 
      'title': 'Register', 
      'errors': errors, 
      'username':username, 
      'email':email, 
      'password':password, 
      'password2':password2 
     }); 
    }else{ 
     console.log('pass the validation.'); 
     var userModel = User.userModel; 
     // var newUser = new userModel({ 
     //  username:username, 
     //  email:email, 
     //  password:password, 
     //  profileimage: profileImageName 
     // }); 

userModel.create({ 
      username:username, 
      email:email, 
      password:password, 
      profileimage: profileImageName 
}, function (err, res) { 
    if (err) return handleError(err); 
    console.log(res); 
    // saved! 
}) 


     //Create User 
     User.createUser(newUser,function(err,user){ 
      if(err){throw err} 
      console.log(user); 
     });//user model 
     // newUser.save(function(err,newUser){ 
     //  if(err){console.log(err);} 
     //  console.log(newUser); 
     // }); 

     //success Message 
     req.flash('success','you are now registered and may log in'); 
     //redirect to the home page 
     res.location('/'); 
     res.redirect('/'); 
    } 
}); 




router.get('/login', function(req, res, next) { 
    res.render('login',{ 
     'title': 'Login' 
    }); 
}); 
module.exports = router; 
+0

スキーマ定義などの他の詳細を追加できますか?私は上記を試して、それは私のために動作します。 –

+0

もちろん、私はそれを追加しました。チェックは – franklee

+0

モジュールのエクスポートで 'userModel'宣言を削除しようとしました。代わりに 'mongoose.model( 'User'、UserSchema)'をあなたのスキーマを宣言した後に置いてください。次に、この 'User = mongoose.model( 'User');を実行してコントローラ内のモデルを取得してください。 –

答えて

0

スキーマ/メソッド/エクスポートを0の外に移動しました。と動作します。

db.on('error', console.error.bind(console, 'connection error:')); 

db.once('open', function() {//when connected 
    console.log('connected to mongo db'); 
}); 

var UserSchema = mongoose.Schema({ 
username: { 
    type: String, 
    index: true 
}, 
email: { 
    type: String 
}, 
password: { 
    type: String, 
    required: true, 
    bcrypt: true 

}, 
profileimage: { 
    type: String 
} 
}, {timestamps: 'created_at'}); 

//add "speak" functionality to our documents: 
UserSchema.methods.speak = function() { 
var greeting = this.name 
    ? "His name is " + this.name 
    : "I do not have a nanme"; 
console.log(greeting); 
}; 

module.exports = { 
userModel: mongoose.model('User', UserSchema), 
createUser: function (newUser, callback) { 
    bcrypt.hash(newUser.password, null, null, function (err, hash) { 
     // Store hash in your password DB. 
     newUser.password = hash; 
     newUser.save(callback); 

    }); 

} 
}; 
関連する問題