【发布时间】:2026-01-15 18:10:01
【问题描述】:
我想知道,是否可以制作将发送到 MongoDB 的自定义 req.body。就我而言,我有这样的 req.body :{ f_name: 'John', l_name: 'Doe', phone: '4521234892345' }
但是,我期望的是:
{
"f_name": {
"type": "text",
"value": "John"
},
"l_name": {
"type": "text",
"value": "Doe"
},
"phone": {
"type": "number",
"value": "212348923"
}
}
type 的值来自 HTML <input /> 的表单。
例如:<input type="text" name="f_name" value="John">
和 <input type="number" name="phone" value="212348923">
我的后台:
app.post("/api/leads/:userId/:formId", async (req, res) => {
console.log(req.body);
});
我的另一个后端:
app.get("/view/:id", async (req, res) => {
const result = await Form.findOne({ _id: req.params.id });
// console.log(result);
// console.log(err)
const data = JSON.parse(JSON.stringify(result));
res.render("form", {
data
});
});
我的前端(form.pug):
form(action='/api/leads/'+data._user+'/'+data._id, method='POST')
mixin FieldGroup(id, type, label, text)
div(classname="field-group")
.field-group__inner
if label
label(classname="capitalize")= text
| :
.field-row__inner
input(id=id classname="input input--text" type=type name=text.toLowerCase().split(' ').join('_'))
else
.field-row__inner
input(id=id classname="input input--text" name=text.toLowerCase().split(' ').join('_') type=type placeholder=text)
each val, index in data.formElement.fieldRows
.field-row
.field-row__inner
each fieldGroup, i in val.fieldGroups
+FieldGroup(fieldGroup.id, fieldGroup.type, fieldGroup.useLabel, fieldGroup.labelPlaceholder)
.is-center.m-top-30
button.button.is-success(type='submit') Submit
【问题讨论】:
-
是的,可能,但您必须根据您在后端、服务器端的要求进行更改,从哪里保存。
-
@saikatchakrabortty 你能给我一些线索或建议吗?
-
请编辑问题并添加您的后端结构和架构。
-
@saikatchakrabortty 已更新
标签: javascript node.js mongodb mongoose