Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

122
Vistas
Nodejs exports returns undefined on mongoose Insertion

I have created nodejs application by organising as module structure , The problem I am facing is that a mongodb insertion return undefined value from one of my controller, The issue I found is that my async funtion doesn't wait to complete my mongodb operation But I could not find a solution for that, my route and controller code is given below

route.js

const {
    createEvent, editEvent
}  = require('./controller');

router.post("/event/create",  validateEventManage, isRequestValidated, async(req, res) => {
    let data = {};
    data.body = req.body;

    try{
        let event = await createEvent(req.body);
        console.log(event) // returned undefined
        data.event = event;
        res.status(200).json(data);
    }catch(error){
        console.log(error)
        res.status(200).json({error:error});
    }

    
});

controller.js

exports.createEvent  = async(data) => {
    // return "test" // This works correctly
    const eventObj = {
        name            : data.name,
        description     : data.desc,
        type            : data.type,
        startDate       : new Date()
    }

    const event = await new Event(eventObj);

    await event.save((error,event)=>{
        if(error) {
             return error;
        }
        if(event){
            return event;     
        } 
     });

}
over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

You should not await the new Event constructor.
Also, since you are using async - await you can remove the callback from the save and try ... catch the error to handle it:

exports.createEvent = async (data) => {
    // return "test" // This works correctly
    const eventObj = {
      name: data.name,
      description: data.desc,
      type: data.type,
      startDate: new Date(),
    };
  
    try {
      const event = new Event(eventObj);
      await event.save();
      return event;
    } catch (error) {
      return error;
    }
  };  
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda