首页 > 解决方案 > 如何使用 express/nodejs 将下拉表单数据发布到 MongoDB?

问题描述

抱歉,如果这是一个愚蠢的问题,我对表达和 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.jsformsrestexpresspost

解决方案


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

然后,在每个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>

推荐阅读