自定义req.body Nodejs

时间:2018-02-26 04:45:31

标签: javascript node.js mongodb mongoose

我想知道,是否可以制作自定义的req.body,它将被发送到MongoDB。就我而言,我有这样的需求:
{ 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

0 个答案:

没有答案