[英]Mongoose schema constructor not recognized
我有一個使用Mongoose和User模式的Node服務器。 我正在嘗試編寫注冊功能,但是出現以下錯誤:
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;
我對Java語言不是很熟悉,所以這可能是我在方法中其他地方錯過的簡單錯字。 但是,我確實研究了所有可能發現的類似錯誤的問題,這些建議的更改未能解決問題。
我認為您無法使用架構保存新對象。 嘗試這種方式:
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,否則將引發錯誤,或者您可以跳過statics並直接分配函數,如下所示:
module.exports.signup = function(...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.