Reputation: 6657
I have a Node server using Mongoose, with a User schema. I am trying to write a signup function, but I am getting the following error:
TypeError: this is not a constructor
This is occurring in this code:
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;
I am not very familiar with Javascript, so it could be a simple typo I missed somewhere else in the method. However, I did research any problems I could find with similar error the suggested changes did not fix the problem.
Upvotes: 0
Views: 1463
Reputation: 876
I think you can not save a new object using schema. Try this way:
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");
});
}
hope this work
EDIT: plese make sure model.statics exists, otherwise it will raise error or you can skip statics and assign the function directly as below:
module.exports.signup = function(...
Upvotes: 2