简体   繁体   English

Nodejs 导出在猫鼬插入时返回未定义

[英]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我通过组织模块结构创建了nodejs应用程序,我面临的问题是mongodb插入从我的一个控制器返回未定义的值,我发现的问题是我的异步函数没有等待完成我的mongodb操作但是我找不到解决方案,我的路由和控制器代码如下

route.js路由.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控制器.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;     
        } 
     });

}

You should not await the new Event constructor.您不应await new Event构造函数。
Also, since you are using async - await you can remove the callback from the save and try ... catch the error to handle it:此外,由于您使用的是async - await您可以从save中删除回调并try ... catch错误以处理它:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM