简体   繁体   English

在nodejs中使用异步等待function和mongoose查询

[英]Use async await function with mongoose query in nodejs

I tried to make async and await function in mongoose.我试图在 mongoose 中进行异步并等待 function。 but in one case it simply didn't work while in another case it shows syntax error.但在一种情况下它根本不起作用,而在另一种情况下它显示语法错误。

here is my code这是我的代码

exports.updateDiscount= async (_id,discount) =>
{
    try
    {
        console.log(_id,discount);
        Discount.findOne({_id},(err,user) =>
        {
            if(user)
            {
              user.discountRate=parseFloat(discount);
              let saveUser= await user.save();
              if(saveUser)
              {
                  console.log("Discount saved");
                  return true
              }
            }
        })
    } catch(err)
    {
        console.log(err);
    }
}

I am using the thing function in another module我在另一个模块中使用 function


if( updateDiscount(item.userid,discount) === true)
   {
   }

Solution::解决方案::

exports.updateDiscount= async (_id,discount) =>
{
    try
    {
        console.log(_id,discount);
        let user = await Discount.findOne({_id});
        
            if(!!user)
            {
              user.discountRate=parseFloat(discount);
              let saveUser= await user.save();
              if(!!saveUser)
              {
                  console.log("Discount saved");
                  return true
              }
            }
    } catch(err)
    {
        console.log(err);
    }
}

you need to await the function你需要等待 function

const answer = await updateDiscount(item.userid,discount);
if(answer) {
}

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

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