I want to know, is it possible to make custom req.body which is will be send to MongoDB. In my case, I have req.body like this :
{ f_name: 'John', l_name: 'Doe', phone: '4521234892345' }
But, what i expected is :
{
"f_name": {
"type": "text",
"value": "John"
},
"l_name": {
"type": "text",
"value": "Doe"
},
"phone": {
"type": "number",
"value": "212348923"
}
}
The value of type
are coming from HTML <input />
in a form.
For example :
<input type="text" name="f_name" value="John">
and<input type="number" name="phone" value="212348923">
My backend :
app.post("/api/leads/:userId/:formId", async (req, res) => {
console.log(req.body);
});
My other backend:
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
});
});
My Frontend(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
I mean, if you have control of the front end, just make your form mirror your data model. Otherwise, transform you data at your server before it makes a call to your database. It's what we all have to do.
Your HTML in a form. Like :
<input type="hidden" name="f_name[type]" value="text">
<input type="text" name="f_name[value]" value="John">
and in your app.js body-parser extended should be true like
bodyParser.urlencoded({ extended: true });
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.