Here's the code for a new user:
var User = mongoose.model('User', userSchema);
var usr = new User({ username: 'bob', email: '[email protected]', password: 'secret' });
Here's the code for checking login.
passport.use(new LocalStrategy(function(username, password, done) {
User.findOne({ username: username }, function(err, user) {
if (err) { return done(err); }
if (!user) { return done(null, false, { message: 'Unknown user ' + username }); }
user.comparePassword(password, function(err, isMatch) {
if (err) return done(err);
if(isMatch) {
return done(null, user);
} else {
return done(null, false, { message: 'Invalid password' });
}
});
});
}));
If the username doesn't exist, it says "Unknown user __________"
Instead of saying unknown user, I want to create a new user in the database. How do I modify this code to do that?
I'd like to create a new user with the login info they entered if that login name doesn't already exist.
Update
I'm trying this and it's not working. bob5 isn't saving to the database.
passport.use(new LocalStrategy(function(username, password, done) {
User.findOne({ username: username }, function(err, user) {
if (err) { return done(err); }
if (!user) { usr = new User({ username: 'bob5', email: '[email protected]', password: 'secret' });
usr.save(function(err) {
if(err) {
console.log(err);
} else {
console.log('user: ' + usr.username + " saved.");
}
});
If I type this, bob99 gets saved to the database. So I can create a user... I just need to pass the arguments to it within the if statement (I think).
usr = new User({ username: 'bob99', email: '[email protected]', password: 'secret' });
usr.save(function(err) {
if(err) {
console.log(err);
} else {
console.log('user: ' + usr.username + " saved.");
}
});
return done(...)do an insert.