类型错误:用户不是构造函数 - Mongoose Node.js Express-Validator [英] TypeError: User is not a constructor - Mongoose Node.js Express-Validator
问题描述
我收到此错误:
用户不是构造函数类型错误"
"User is not a constructor TypeError"
我无法找出代码中有什么问题.任何建议表示赞赏!
I couldn't find out what is wrong in the code. Any advice is appreciated!!
routes/users.js
// Initialised user.js into users.js
// var User = require('../models/user');
if (errors) {
// code here is working
} else {
console.log('PASSED'); // logs "passed" msg successfully
var newUser = new User({
name: name,
email: email,
phone: phone,
password: password2
});
User.createUser(newUser, function (err, user) {
if (err) throw err;
console.log(user);
});
req.flash('success_msg', 'You had been succesfully registered! Try signin.');
res.redirect('/users/signin');
}
models/user.js
var mongoose = require('mongoose');
var bcrypt = require('bcrypt');
var UserScheme = mongoose.Schema({
name: {
type: String,
index: true
},
email: {
type: String
},
phone: {
type: String
},
password: {
type: String
}
});
var User = module.export = mongoose.model('User', UserScheme);
// encrypting password into hash
module.export.createUser = function(newUser, callback){
bcrypt.genSalt(saltRounds, function(err, salt) {
bcrypt.hash(newUser.password, salt, function(err, hash) {
newUser.password = hash;
newUser.save(callback);
});
});
};
如果需要更多代码,我可以更新帖子.
I can update the post if more code is necessary.
推荐答案
你需要把module.export
改为module.exports
此处的节点文档 * 请注意,导出是指向模块的快捷方式.出口.module.exports 是需要模块时返回的默认对象.在您的示例中,您创建了名为 export 的模块的新属性.这里有一篇博客文章描述了这种关系出口和module.exports.
node docs here * note that exports is a shortcut that points to module.exports. module.exports is the default object that gets returned when the module is required. In your example you have created a new property of module that is called export. here is a blog post that describes the relationship of exports and module.exports.
考虑以下示例:
stack: cat ./49275169.js
console.log('export', module.export)
console.log('exports', module.exports)
stack: node ./49275169.js
export undefined
exports {}
stack:
这是一个猫鼬的例子:
stack: cat module.js
const mongoose = require('mongoose')
const Schema = mongoose.Schema
const schema = new Schema({ name: String })
const User = module.exports = mongoose.model('Users', schema)
module.exports.createUser = function (newUser, callback) {
console.log(new User({ name: 'Rohit' }))
}
stack: cat ./49275169.js
const mongoose = require('mongoose')
const User = require('./module')
mongoose.connect('mongodb://localhost/test')
const user = new User({
name: 'Branford'
})
user.save((err, doc) => {
if (err) { return console.error(err) }
mongoose.connection.close()
return console.log(doc)
})
User.createUser()
stack: node ./49275169.js
{ name: 'Rohit', _id: 5aa9138819d660182938b128 }
{ name: 'Branford', _id: 5aa9138819d660182938b127, __v: 0 }
stack:
这篇关于类型错误:用户不是构造函数 - Mongoose Node.js Express-Validator的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!