如何使用express / nodejs将下拉表单数据发布到MongoDB?

问题描述 投票:0回答:1

抱歉,这是一个愚蠢的问题,我表示和mongodb / mongoose超级陌生,所以不确定我在做什么错。我正在尝试提供一些下拉菜单,用户可以在其中从每个下拉菜单中进行选择,然后单击“提交”以向我的数据库发送POST请求。我使用它来输入您自己的数据的表单,但是我只希望用户能够从下拉菜单中进行选择...

这是我尝试从以下位置创建POST请求的下拉表单:

<form action="/environments" method="POST"></form>
    <select>
        <% environments.forEach(function(environment){ %>
        <option value="name"><%= environment.name %></option>
        <% }); %>
    </select>
    <select>
        <% environments.forEach(function(environment){ %>
        <option value="region"><%= environment.region %></option>
        <% }); %>
    </select>
    <input type="submit" />
</form>

这是我的app.js

var express = require("express"),
  app = express(),
  mongoose = require("mongoose"),
  bodyParser = require("body-parser");

mongoose.connect("mongodb://localhost/epims", {
  useNewUrlParser: true,
  useUnifiedTopology: true
});
app.use(bodyParser.urlencoded({ extended: true }));
app.set("view engine", "ejs");

//schema setup
var environmentSchema = new mongoose.Schema({
  name: String,
  region: String
});

var Environment = mongoose.model("Environment", environmentSchema);

//DISPLAY ALL ENVIRONMENTS IN DB
app.get("/environments", function(req, res) {
  //get all environments from db
  Environment.find({}, function(err, allEnvironments) {
    if (err) {
      console.log(err);
    } else {
      res.render("environments", { environments: allEnvironments });
    }
  });
});

//POST FORM DATA TO DB
app.post("/environments", function(req, res) {
  //get data from form and add to db
  var name = req.body.name;
  var region = req.body.region;
  var newEnvironment = { name: name, region: region };
  //create new env and save to db
  Environment.create(newEnvironment, function(err, newlyCreated) {
    if (err) {
      console.log(err);
    } else {
      //redirect back to environments
      res.redirect("/environments");
    }
  });
});

node.js forms rest express post
1个回答
0
投票

您必须为每个选择标签设置名称。对于您的情况,它将是nameregion,因为这是您要回发到服务器的值。

然后,在每个option标记的每个select标记中,您必须为其设置值,如果设置<option value="name"><%= environment.name %></option>,则意味着对于每个选择,您总是获得的值为name

最后,ejs代码(我认为是这样:

<form action="/environments" method="POST"></form>
    <select name="name">
        <% environments.forEach(function(environment){ %>
        <option value="<%= environment.name %>"><%= environment.name %></option>
        <% }); %>
    </select>
    <select name="region">
        <% environments.forEach(function(environment){ %>
        <option value="<%= environment.region %>"><%= environment.region %></option>
        <% }); %>
    </select>
    <input type="submit" />
</form>
© www.soinside.com 2019 - 2024. All rights reserved.