无法通过注册表单将用户添加到数据库

时间:2019-04-29 21:16:55

标签: javascript node.js mongodb

我有一个注册表格,要求用户将数据输入某些字段,例如用户名,passowrd,电子邮件,firstName,lastName。我正在尝试将用户输入的信息存储到我的mongoDB数据库中,但是它不起作用。我得到的错误是: TypeError:UserDB.insert不是函数

profileController-

router.post('/register', urlencodedParser, function(req, res){
  UserDB.insert(req.body.userID, req.body.username, req.body.password, req.body.firstName, req.body.lastName, req.body.email);
  res.redirect('login');
});

register.ejs-

</section>
        <form action='/register' method='POST'>
          <p><b>Username:</b></p>
          <input type="text" name='username'><br>

          <p><b>Password:</b></p>
          <input type="password" name='password'><br>

          <p><b>Email:</b></p>
          <input type="email" name='email'><br>

          <p><b>First Name:</b></p>
          <input type="text" name='firstName'><br>

          <p><b>Last Name:</b></p>
          <input type="text" name='lastName'><br>

          <br>
          <input type="submit" value='Submit'>
        </form>
      </form>

UserDB-

var userdbSchema = new Schema({
  userID: {type: String, required: true},
  username: {type: String, required: true},
  password: {type: String, required: true},
  firstName: {type: String, required: true},
  lastName: {type: String, required: true},
  email: {type: String, required: true},
},{collection: 'User'});

module.exports = mongoose.model('User', userdbSchema);

2 个答案:

答案 0 :(得分:0)

您应该将mongoose models try { BufferedReader br = new BufferedReader(new FileReader(filePath)); String line; while ((line = br.readLine()) != null) { if (line.startsWith("h")){ lineStore.add(line); DefaultHttpDataSourceFactory dataSourceFactory = new DefaultHttpDataSourceFactory("exoplayer_video"); for (String url : lineStore) { mediaSources.add(new HlsMediaSource.Factory(dataSourceFactory).createMediaSource(Uri.parse(url))); } ConcatenatingMediaSource concatenatingMediaSource = new ConcatenatingMediaSource(mediaSources.toArray(new MediaSource[mediaSources.size()])); exoPlayerView.setPlayer(exoPlayer); exoPlayer.prepare(concatenatingMediaSource); exoPlayer.setPlayWhenReady(true); 而不是UserDB.create

语法也不同。您应该传递一个对象而不是参数列表:

UserDB.insert

您还可以考虑在router.post('/register', urlencodedParser, function(req, res) { UserDB.insert({ userID: req.body.userID, username: req.body.username, password: req.body.password, firstName: req.body.firstName, lastName: req.body.lastName, email: req.body.email }); res.redirect('login'); }); 函数的回调中处理成功和错误情况

答案 1 :(得分:0)

您正在使用猫鼬与Mongodb进行交互。那里没有“插入”方法,您必须使用create或save方法来保存更改。请参阅https://mongoosejs.com/docs/models.html

代码如下所示:

UserDB.create({
  userID:req.body.userID,
  username:req.body.username
}).then(()=>{})

request.body参数与猫鼬模型同名,您也可以这样做

UserDB.create(req.body).then(()=>{})