Search code examples
node.jspassport-local

MissingUsernameError: No username was given - Unsure where i'm going wrong


I'm using Node.js with Mongoose and Passport trying to get the user to save to the DB but keep encountering the error where No Username was given. I can get it to save if just using using username and password but as soon as I try to add more fields I get the issue. This is the code I have:

app.js

const userSchema = new mongoose.Schema ({    
  firstname: String,
  lastname: String,
  username: String,
  password: String,
  userLevel: {type: Number},
  profileImage: String,
  title: String
});

//ENABLE PASSPORT LOCAL
userSchema.plugin(passportLocalMongoose, {
  selectFields: ' firstname lastname username  password userLevel profileImage title'
});

//CREATE NEW model
const User = new mongoose.model("User", userSchema);

passport.use(User.createStrategy());

passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());

app.get('/control', (res, req) => {
  if (req.isAuthenticated()) {
    res.render('control');
  } else {
    res.redirect('/login')
  }
});

app.post("/register", (req, res) => {
  User.register(new User(
    {firstname: req.body.firstname},
    {lastname: req.body.lastname},
    {username:req.body.username},
    {userLevel: 1},
    {profileImage:"not set"},
    {title:"not set"}
  ),
  req.body.password,
  (err, user) => {
    if (err) {
      console.log(err);
      console.log(req.body.username);
    } else {
      passport.authenticate('local')(req, res, () =>{
        res.redirect('/control');
      });
    }
  });
});

Solution

  • Figured it out! I was using individual objects rather that just the one object :

    User.register((
        {firstname: req.body.firstname,
        lastname: req.body.lastname,
        username: req.body.username,
        userLevel: 1,
        profileImage:"not set",
        title:"not set"
      }),
        req.body.password,
        (err, user) => {
        if (err) {
          console.log(err);
          console.log(req.body.username);
        } else {
          passport.authenticate('local')(req, res, () =>{
            res.redirect('/control');
          });
        }
      });
    });