从表单保存信息到MongoDB数据库?

时间:2017-10-17 00:26:13

标签: javascript mongodb express

我想将从html表单中捕获的信息保存在MongoDB数据库中,我有以下代码:

<!DOCTYPE html>
<html>
 <head>
 <title>Intro to Node and MongoDB</title>
 </head>

 <body>
 <h1>Into to Node and MongoDB</h1>
 <form method="post" action="/addname">
 <label>Enter Your Name</label><br>
 <input type="text" name="firstName" placeholder="Enter first name..." required>
 <input type="text" name="lastName" placeholder="Enter last name..." required>
 <input type="submit" value="Add Name">
 </form>
 </body>
</html>

以下javascript代码将是我的app.js

var express = require("express");
var app = express();
var port = 3000;

var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));


var mongoose = require("mongoose");
/*
mongoose.Promise = global.Promise;mongoose.connect("mongodb://localhost:27017/node-demo");
*/

var promise = mongoose.connect('mongodb://localhost:27017/node-demo', {
  useMongoClient: true,
  /* other options */
});


var nameSchema = new mongoose.Schema({
 firstName: String,
 lastName: String
});

var User = mongoose.model("User", nameSchema);

app.use("/", (req, res) => {
 res.sendFile(__dirname + "/index.html");
});



app.post("/addname", (req, res) => {
 var myData = new User(req.body);
 myData.save()
 .then(item => {
 res.send("item saved to database");
 })
 .catch(err => {
 res.status(400).send("unable to save to database");
 });
});



app.listen(port, () => {
 console.log("Server listening on port " + port);
});

显然,post请求正在运行,填写字段并按下输入类型submit,但是当检查数据库为空时,就像创建它时一样。有谁知道为什么我不保存这些信息?

1 个答案:

答案 0 :(得分:0)

我在这里运行您的代码并且未调用app.post。这是因为您使用app.use发送index.htmlapp.use用于将middleware绑定到您的应用程序。相反,你应该使用app.get,它告诉express要监听/的请求并在看到它时运行该函数。

app.get("/", (req, res) => {
 res.sendFile(__dirname + "/index.html");
});