Necesito ayuda con mi backend. Estoy usando cartero y aquí está el modelo de mi 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() } } ]Lo que intento hacer es insertar documentos en la matriz de agentes, pero recibo algunos errores.
Las rutas y los controladores son los siguientes:
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 }) }) }Este es el error que estoy recibiendo: (nodo: 9916) UnhandledPromiseRejectionWarning: CastError: Cast to ObjectId falló para el valor "{ departmentId: '60e27549c36af1272812c4e3' }" (tipo de objeto) en la ruta "_id" para el modelo "Departamento"
El objetivo es buscar la identificación del departamento y empujará la identificación del agente que ya adquirí.
Probar
Cambio
return Department.findById({departmentId: params.departmentId}).
a
return Department.findById(params.departmentId)
findById aceptar solo id no objeto
Gracias Tushar! Eres muy útil.
Pude encontrar la respuesta utilizando el enlace que proporcionó y me di cuenta de que estoy cometiendo algunos errores con el código en sí. Jajajaja
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 }) }) }Ahora está funcionando.