[英]How to POST dropdown form data to MongoDB using express/nodejs?
對不起,如果這是一個愚蠢的問題,我是表達和 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
和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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.