Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

232
Visualizações
MongoDb: Getting error while pushing documents in an array

I need help with my backend. I'm using postman and here's the model of my back end:

name: {
        type: String,
        required: [true, 'Department Name is Required']
    },
    description: {
        type: String,
        required: [true, 'Description is Required']
    },
agents: [
        {
            agentId: {
                type: String,
                required: [true, 'Agent ID is Required']
            },
            createdOn: {
                type: String,
                default: new Date()
            }
        }
]

What I'm trying to do is push documents in agents array but I'm getting some errors.

The routes and controllers are as follows:

Routes:
router.post('/enroll', (req, res) => {
    UserController.enroll(req.body).then(result => res.send(result))
});
Controllers:
module.exports.enroll = (params) => {
    return Department.findById({departmentId: params.departmentId}).then(department => {
        department.agents.push({userId: params.userId})

        return department.save().then((department, error) => {
            return (err) ? false : true
        })
    })
}

This is the error that I'm getting: (node:9916) UnhandledPromiseRejectionWarning: CastError: Cast to ObjectId failed for value "{ departmentId: '60e27549c36af1272812c4e3' }" (type Object) at path "_id" for model "Department"

The target is look for the department id and will push the agent id that I already acquire.

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

Try

Change

return Department.findById({departmentId: params.departmentId}).

to

return Department.findById(params.departmentId)


findById accept only id not Object

over 4 years ago · Santiago Trujillo Relatório

0

Thanks Tushar! You're very helpful.

I was able to find the answer using the link you've provided and realized that I'm making some mistakes with the code itself. Hahahaha

I've modified routes to:
router.post('/enroll/:id', (req, res) => {
    const params = {
        departmentId: req.params.id,
       agentId: req.body.agentId
    }
    
    UserController.enroll(params).then(department => res.send(department))
});
Then, some of the lines in my controllers too:
module.exports.enroll = (params) => {
    return Department.findById(params.departmentId).then(department => {
        department.agents.push({agentId: params.agentId})

        return department.save().then((department, error) => {
            return (error) ? false : true
        })
    })
}

It is now working.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda