MissingUsernameError:未提供用户名-不确定我要去哪里

时间:2019-04-24 16:10:06

标签: node.js passport-local

我正在将Node.js与Mongoose和Passport结合使用,试图使用户保存到数据库,但一直遇到未提供用户名的错误。如果仅使用用户名和密码,就可以保存它,但是当我尝试添加更多字段时,就会遇到问题。这是我的代码:

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');
      });
    }
  });
});

1 个答案:

答案 0 :(得分:0)

想通了!我使用的是单个对象,而不是一个对象:

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');
      });
    }
  });
});