II制作用户模型,并希望在users.js路由文件中使用它。但它显示 userModel不是函数。有谁知道这里发生了什么?感谢
//我在models / user.js中的用户模型
var mongoose = require('mongoose');
var bcrypt = require('bcrypt-nodejs');
var url = 'mongodb://fr:fran98@ds013250.mlab.com: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);
});
}
};
});
//路由/ 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);
});
ADDS: //关于routes / users.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)
我将架构/方法/导出移到db.once
之外并且它可以正常工作。
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);
});
}
};