node.js - 如何使用 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");
}
});
});
解决方案
您必须为每个选择标签设置名称。对于您的情况,它将是name
and 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>
推荐阅读
- r - 在R中按多个条件排列
- node.js - AWS Elastic Beanstalk 不会从 nodejs 应用程序的公共文件夹中加载静态文件
- laravel-5 - Laravel 应用程序(AWS 服务器)中的关键缓存问题
- javascript - 使用 recorder.js 以低 kbps 录制音频
- python - 按模型中计算的计算字段对记录进行排序
- rust - 如何在循环间隔内同时运行一组函数,而不使用 Tokio 同时运行相同的函数?
- javascript - 如何使用反应钩子实现多个复选框
- html - CSS 字体包括未在浏览器中显示
- json - Django rest API 格式化数据
- c# - 用户点击恶意链接时易受攻击