解析发布的对象数组,Express

Parsing posted object array, Express

我需要使用 Express 从表单解析数据:

invoiceRouter.post('/', async (req,res) => {
  console.log(req.body);
  let invoice = new Invoice();
  invoice = req.body;
  invoice.status = 0;
  //save
  res.redirect('/invoices');
});

当我登录时,对象数组被读取为值列表:

{
createdDate: '2021-10-15',
invoiceRows: [ 'Title3', '2', 'Title2', '3' ]
}

但它无法将 invoiceRows 读取为 2 的数组,因此我正在努力将其解析为数组以保存它。 当我设置 extended: false 时,我可以从 req.body 看到以下结果:

[Object: null prototype] {
  createdDate: '2021-10-15',
  'invoiceRows[0].productTitle': 'Title2',
  'invoiceRows[0].unitPrice': '2',
  'invoiceRows[1].productTitle': 'Title3',
  'invoiceRows[1].unitPrice': '2'
}

我正在使用的架构:

const invoiceSchema = new mongoose.Schema({
    createdDate: {
        type: Date,
        required: true
    },
    status: {
      type: Number,
      required: true
    },
    invoiceRows: [{
      productTitle: String,
      unitPrice: Number
    }]
});

问题:为了从父对象中的 req.body 获取对象数组,我做错了什么?

在您的 req.body 中,您应该会收到如下消息(根据您的模型架构)。让你的前端像下面这样发送数据。

 {
   createdDate: '2021-10-15',
   invoiceRows: [ { productTitle :'Title1', unitPrice : 2}, { productTitle :'Title2', unitPrice : 3} ]
}