Search code examples
node.jsmulter

how to change an object to array in postman in order to solve "TypeError: tasks.map is not a function"


im creating a api that should upload a image with multer but im getting tasks.map is not a function, here is the code:

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'})
        
       
    }
})

my console.log for the req.body is this :

[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'
  }
}

how you can see it is an object but I need it to be an array, how can I solve this?

and here is my request:

enter image description here


Solution

  • Your tasks object is not an array (as you can see in the console.log()), so you can not use map on it.

    If you want to send it as an array, try to send data in Postman like this:

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

    So, just add [0] after the tasks.