データベース内のすべての製品について、投稿リクエストで mongodb を検索しようとしています。投稿リクエスト以外はすべて機能しています。リクエストは完了しますが、データは返されません。データベースに問題はありません。
const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const app = express();
app.set("view engine", "ejs");
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static("public"));
mongoose.connect(
"mongodb+srv://x:[email protected]/productsDB?
retryWrites=true&w=majority",
{
useNewUrlParser: true,
useUnifiedTopology: true,
}
);
const productsSchema = {
name: String,
price: Number,
img: String,
};
const Product = mongoose.model("product", productsSchema);
app.get("/", function (req, res) {
res.send(__dirname + "/index.html");
});
app.post("/", function (req, res) {
const productName = req.body.productName;
Product.find({ name: productName }, function (err, foundProducts) {
res.render("home", {
name: foundProducts.name,
price: foundProducts.price,
img: foundProducts.img,
});
});
});
app.listen(3001, function () {
console.log("Server started successfully");
});
index.html は他のものよりも先に表示されます
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8" />
<title>X</title>
</head>
<body>
<form action="/" method="post">
<input
type="text"
name="productName"
placeholder="Search for a product"
/>
<button type="submit" name="Search">Search</button>
</form>
</body>
</html>
製品の検索時に表示される home.ejs
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>X</title>
</head>
<body>
<h1><%= name %></h1>
<% var imgwostr = img; %>
<% imgwostr = str.replace(/^"|"$/g, ""); %>
<img src="<%= imgwostr %>" alt="">
<p><%= price %></p>
</body>
</html>
------------------------
問題は、データベースが 1 つのドキュメントとして扱うドキュメントのリストを返すことです。
foundProducts オブジェクトは、実際には Product 型の配列です。製品が 1 つしかない場合でも、配列であることに変わりはありません。値を取得するには、取得したい項目のインデックスを指定する必要があります。
次のようなものが機能するはずです:
Product.find({ name: productName }, function (err, foundProducts) {
const product = foundProducts[0];
if (!product) {
res.render('notfound');
}
res.render("home", {
name: product.name,
price: product.price,
img: product.img,
});
}
商品が見つからない場合は、表示するものが何もないため、別のページをレンダリングする必要があることに注意してください。
0