2016-04-14 8 views
0

II kullanıcı modeli hazırlar ve bunu kullanamazlar user.js route file.but bana gösterir userModel işlevi değil. Burada neler olduğunu bilen var mı? rotalar/kullanıcılar hakkında // daha: modellerinde TeşekkürBir model kullanarak örnek oluşturma 'işlev değil' (düğüm kullanarak düğüm)

// my Kullanıcı model/

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); 
    }); 

KATIYOR

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

user.js. 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

Şema tanımı vb. Gibi diğer ayrıntıları ekleyebilir misiniz? Yukarıdakileri denedim ve benim için çalışıyor. –

+0

tabiki, ekledim. – franklee

+0

bir kontrol var modül ihracatında 'userModel' beyanını kaldırmayı deneyin. Bunun yerine şema ilan bittikten sonra 'mongoose.model ('Kullanıcı', UserSchema)' yerine. Daha sonra modelinizi kontrol ederek bu 'Kullanıcı = mongoose.model ('Kullanıcı');' –

cevap

0

Şema/yöntem/dışa aktarma 0 dışındave işe yarıyor.

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); 

    }); 

} 
};