Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

124
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!