如何在邮递员中将对象更改为数组以解决“TypeError:tasks.map is not a function”

时间:2021-04-12 12:41:34

标签: node.js multer

我正在创建一个应该使用 multer 上传图像的 api,但我正在获取 tasks.map 不是一个函数,这是代码:

router.post('/',uploads.any(), async (req, res) => {

    try{
        const { title, description, tasks } = req.body

        const project =  await Project.create({title, description, user: req.userId });
       
        console.log(req.body)
       await Promise.all(tasks.map( async task => {
            const projectTask = new Task({...task, project: project._id})

           await projectTask.save()

           project.tasks.push(projectTask)
        }))

        await project.save()
        return res.send({ project })
    } catch(err) {
        console.log(err)
        return res.status(400).send({error: 'Error creating new project'})
        
       
    }
})

我的 req.body 的 console.log 是这样的:

[Object: null prototype] {
  title: 'titulo',
  description: 'tinha feito errado',
  tasks: [Object: null prototype] {
    title: 'testee form',
    descriptiom: 'tomara que funcione',
    dicionario: [Object: null prototype] { nome: 'Teste' },
    assignedTo: '605df6eab581542e58d447ac'
  }
}

你怎么能看到它是一个对象,但我需要它是一个数组,我该如何解决这个问题?

这是我的要求:

enter image description here

1 个答案:

答案 0 :(得分:1)

您的 tasks 对象不是数组(如您在 console.log() 中所见),因此您不能在其上使用 map

如果你想把它作为一个数组发送,试着像这样在 Postman 中发送数据:

tasks[0][title]
tasks[0][description]
...

因此,只需在 [0] 后添加 tasks