表单的第一个和第二个输入会返回“ null”

时间:2018-10-27 23:07:27

标签: javascript node.js mongodb forms backend

所以基本上我想创建一个收集用户信息并将其存储在数据库中的表单。很好的问题是,由于某种原因,“ fname”和“ name”(来自表单的前两个输入)会返回“ null”,即使它们已经填充了文本。那里的问题是,由于已经存在具有给定'lname'和'fname'的用户-在这种情况下为'null',因此我无法添加其他用户。对我来说,最奇怪的部分是,其他输入似乎没有任何问题。任何帮助/建议表示赞赏。

我的user.js模型:

var mongoose = require("mongoose");

var UserSchema = new mongoose.Schema({
   firstName: {type: String, unique:true},
   lastName: {type: String, unique:true},
   email: {type: String, unique: true},
   hasVoted: {type: Boolean, default: false}
});


module.exports = mongoose.model("User", UserSchema);

我的表单:

<!DOCTYPE html>
<html>
    <head>
        <title>POll</title>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
        <link rel="stylesheet" href="/stylesheets/landing.css">
        <script src="https://cdnjs.cloudflare.com/ajax/libs/modernizr/2.8.3/modernizr.min.js" type="text/javascript" async></script>
    </head>
    <body>



<div class="row">
    <div style="width: 30%; margin: 25px auto;">
        <form action="/" method="post">
            <div class="form-group">
                <input class="form-control" type="text" name="fname" placeholder="First Name">
            </div>
            <div class="form-group">
                <input class="form-control" type="text" name="lname" placeholder="Last Name">
            </div> 
            <div class="form-group">
                <input class="form-control" type="text" name="email" placeholder="Email">
            </div>
            <div class="form-group">
                <textarea class="form-control" name="comment">Comment(Optional)</textarea>
            </div>
            <div class="form-group">
                <input type="submit" value="Submit">
            </div>
        </form>
    </div>
</div>

我的路线并创建mongodb

var express = require("express");
var router = express.Router();
var User = require("../models/user");

router.get("/", function(req, res){
    res.render("landing");
});

router.post("/", function(req, res){
    // get data from form and add to campgrounds array
    var fname = req.body.fname;
    var lname = req.body.lname;
    var email = req.body.email;
    var comment = req.body.comment;
    var newUser = {fname: fname, lname: lname, email: email, comment: comment};
    // Create a new campground and save to DB
    User.create(newUser, function(err, newlyCreated){
        if(err){
            console.log(err);
        } else {
            console.log(newlyCreated);
            //redirect back to campgrounds page
            res.redirect("/", {user: newlyCreated});
        }
    });
})

module.exports = router;

1 个答案:

答案 0 :(得分:0)

不是吗?

var newUser = {fname: fname, lname: lname, email: email, comment: comment};

是这样

var newUser = {firstName: fname, lastName: lname, email: email, comment: comment};