Home > Blockchain >  Nodejs exports returns undefined on mongoose Insertion
Nodejs exports returns undefined on mongoose Insertion

Time:06-02

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

}

CodePudding user response:

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;
    }
  };  
  • Related