我有一个使用Mongoose的Node服务器,带有User模式。我正在尝试编写注册函数,但是我收到以下错误:
TypeError:这不是构造函数
这在以下代码中发生:
var mongoose = require('mongoose');
var passwordHasher = require('password-hash-and-salt');
var User = new mongoose.Schema({
username: String,
hashedPassword: String,
email: String
});
User.statics.signup = function(un, pw, em, cb){
this.findOne( { $or:[ {'username': un}, {'email': em} ] }, function(err, person){
if (err) cb(false, "Server error");
else if (person == null){
passwordHasher(pw).hash(function(error, hash){
console.log(un, pw, em);
if (error) cb(false, "Server error");
var newUser = new User({ username: un, hashedPassword: hash, email: em});
^ (location of error)
newUser.save(function(err){
if (err) cb(false, "Server error");
else {
cb(true, null);
}
});
});
}
else if (person.email == em && person.username == un) cb(false, "Username and email are taken");
else if (person.email == em) cb(false, "Email is taken");
else if (person.username == un) cb(false, "Username is taken");
});
}
var model = mongoose.model('User', User);
module.exports = model;
我对Javascript不太熟悉,所以它可能是一个简单的拼写错误,我错过了方法中的其他地方。但是,我确实研究了任何我能找到的问题,但是建议的更改没有解决问题。
答案 0 :(得分:2)
我认为您无法使用架构保存新对象。试试这个:
var mongoose = require('mongoose');
var passwordHasher = require('password-hash-and-salt');
var User = new mongoose.Schema({
username: String,
hashedPassword: String,
email: String
});
var model = mongoose.model('User', User);
module.exports = model;
module.exports.statics.signup = function(un, pw, em, cb){
model.findOne( { $or:[ {'username': un}, {'email': em} ] }, function(err, person){
if (err) cb(false, "Server error");
else if (person == null){
passwordHasher(pw).hash(function(error, hash){
console.log(un, pw, em);
if (error) cb(false, "Server error");
var newUser = new model({ username: un, hashedPassword: hash, email: em});
^ (change this)
newUser.save(function(err){
if (err) cb(false, "Server error");
else {
cb(true, null);
}
});
});
}
else if (person.email == em && person.username == un) cb(false, "Username and email are taken");
else if (person.email == em) cb(false, "Email is taken");
else if (person.username == un) cb(false, "Username is taken");
});
}
希望这项工作
编辑:请确保model.statics存在,否则会引发错误 或者您可以跳过静态并直接分配函数,如下所示:
module.exports.signup = function(...