![](/img/trans.png)
[英]How to fetch from backend database to display on frontend using react?
[英]How to programmatically add to an array in database from frontend React
我基本上有这条路线
app.post("/order/:orderId/:productId", async (req, res) => {
const result = await Order.findByIdAndUpdate(
req.params.orderId,
{
$push: {
products: req.params.productId
}
},
{ new: true }
);
res.send(result);
});
我有两个集合,即产品和订单。 例如,目标是获取 id(5ddfc649e1e9e31220ce6a16) 的特定订单,并在此 Orders 集合内的 Array 字段中发布带有 id(5de02c4a0ed3160368b9a550) 的产品。 在 Postman 中,我可以通过在 URL 中添加 ObjectIds 来手动完成,如下所示:
Http://localhost:3000/orders/5ddfc649e1e9e31220ce6a16/5de02c4a0ed3160368b9a550.
我得到这个回应:
{
"products": [
"5ddfb388b14c5b41e0607a5e",
"5de02c4a0ed3160368b9a550" // newly added Product
],
"_id": "5ddfc649e1e9e31220ce6a16",
"issuedBy": "issuedBy",
"collectedBy": "collectedBy",
"quantity": 123,
"createdAt": "2019-11-28T11:48:40.500Z",
"updatedAt": "2019-11-28T11:59:51.659Z",
"__v": 0
}
我的挑战是,如何从 UI(Reactjs) 端以编程方式执行此操作?
// Product Schema
const mongoose = require("mongoose");
const ProductSchema = new mongoose.Schema(
{
name: String,
description: String,
price: Number,
quantity: Number,
supplier: String
},
{ timestamps: true }
);
module.exports = mongoose.model("Product", ProductSchema);
// Orders Schema
const mongoose = require("mongoose");
const OrderSchema = new mongoose.Schema(
{
issuedBy: String,
collectedBy: String,
quantity: Number,
products: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "Product",
required: true
}
]
},
{ timestamps: true }
);
module.exports = mongoose.model("Order", OrderSchema);
我真的很感激任何建议或示例代码片段
我认为你正在寻找的是,你需要从你的前端即 React 应用程序点击这个 API。
http://localhost:3000/orders/<order-id-here>/<product-id-here>
然后为您的订单 ID 和产品 ID 提供动态值。
您可以使用 fetch 访问 api。 更多信息
您可以简单地在前端应用程序中使用一些变量。 因为我不知道您的订单 ID 和产品 ID 是如何生成的,所以您需要检查一下,然后进行类似的检查,
let orderId = someValue
let productId = someOtherValue
let url = "http://localhost:3000/orders/"+orderId+"/"+productId
但我认为关注点是 GET 和 POST 方法。 现在你有app.post
但参数在 URL 中,所以你应该使用 GET 方法,即app.get
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.