简体   繁体   中英

Use async await function with mongoose query in nodejs

I tried to make async and await function in mongoose. 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


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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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