在猫鼬中发送POST请求并处理多个子数组

时间:2020-03-10 17:59:12

标签: node.js mongodb mongoose mongoose-schema

通过猫鼬发送POST请求时出错。我的模型如下

const local_lr_urllog_schema = new Schema(
    {  
        local_parameters: [
            {
                source_url: String,
                abstract:String,
                non_abstract: String,
            }
        ],
        api_parameters: [
            {
                type_of: String,
                domain_name: String,
                comment: String
            }
        ]
    }
);

我的控制器是

const add_records = async (req, res) => {
    const records = new Addlogurl({
        local_parameters: [
          { 
            source_url: req.body.local_parameters[0].source_url, 
            abstract: req.body.local_parameters[0].abstract,
            non_abstract: req.body.local_parameters[0].non_abstract,
          }
        ],
        api_parameters:[
          {
            type_of: req.body.api_parameters[0].type_of,
            domain_name: req.body.api_parameters[0].domain_name,
            comment: req.body.api_parameters[0].comment,
          }
        ]
      });
    try {
        await records.save();
    } catch (err) {
        res.status(messages.status.serverError).json({ errors: err });
        return next(errors);
    }
    res.status(messages.status.OK).json({records: records.toObject({ getters: true })});
};

当我通过UnhandledPromiseRejectionWarning: TypeError: Cannot read property '0' of undefined at add_records传递数组时,出现api_parameters错误。当我注释掉api_parameters时,我可以通过local_parameters发送一个数组。

0 个答案:

没有答案