【问题标题】:(node:17891) UnhandledPromiseRejectionWarning: TypeError: newPay.save is not a function(节点:17891)UnhandledPromiseRejectionWarning:TypeError:newPay.save 不是函数
【发布时间】:2021-02-28 14:19:31
【问题描述】:

控制台正在记录用户,但每当我添加保存方法时,我都会收到上述错误,任何帮助都会很好enter code here 这是我的控制器;

 paymentPost: async(req, res, err)=>{
   let {plan, amount, payID} = req.body
   let userID = req.body
   userID = payID
   if(!payID || !plan || !amount){
    res.json({
      message: "all field required"
    })
   } else{
  await User.findOne({userID}).then(async(userId)=>{
     if(!userId || userID.length<9){
       res.status(400).json({
        message: "No user with this ID",
       })
     }else 
      await Payment.findOne({},async (err, payer)=>{
        if(!payer){
            let newPay = []
            newPay.push(new Payment({
            payID,
            amount,
            plan,
            status:true
      }))
      console.log(newPay)
      return newPay.save()
      .then(res.status(200).json({
        message: "Payment successfull",
        newPay
      }))
       }
     
   })
  }
 },

我只需要用户保存到数据库

【问题讨论】:

  • 修正缩进。此代码在 if/else 语句中缺少大括号。您还应该更新您的问题,以包括任何被抛出的错误,以及您的调试结果,即console.log。您应该包括您在代码运行时实际观察到的内容以及所需的结果。

标签: node.js mongoose


【解决方案1】:

您在同一个函数调用中使用了callbacksasync。 您还引用了数组newPay,它的作用域仅限于回调函数,并且该数组没有名为save 的函数。

将您的实现修改为类似于下面的内容。

 const userId = await User.findOne({userID})
 if(!userId || userID.length<9) {
     return res.status(400).json({ message: "No user with this ID" });
 } else {
     const payer = await Payment.findOne({});
     if(!payer) {
        let payee = new Payment({ payID, amount, plan, status:true });
        await payee.save();
        return res.json({ message: "Payment successfull", newPay });
     }
     return res.json({ message: '?' }); // you also need to send a response here if not payer is found
 }

如果您想将Payment 实例推送到数组中以便在后续调用中检索,只需在创建实例后添加推送即可。

     if(!payer) {
        let payee = new Payment({ payID, amount, plan, status:true });
        await payee.save();
        payees.push(payee);
        return res.json({ message: "Payment successfull", newPay });
     }

数组必须来自外部上下文。即在您的实现中,数组 newPay 的范围为 Payment.findOne 回调函数。

因此,在您的 paymentPost 函数之外(但在需要查找数组的函数范围内),您需要定义数组。例如

//payees array is in scope of both paymentPost and paymentGet
const payees = [];
module.exports = {
     paymentPost: async () => {
         // implementation
         payees.push(payee);
     },

     paymentGet: async (id) => {
         return payees.find(payee => payee.payID === id);
     }
}

【讨论】:

  • 是的,我已经让它以这种方式工作,但我真正想要实现的是将每个唯一付款人的付款保存在他/她自己的 newPay 数组中,这样我就可以查询每个用户的付款历史,如果我想
  • @MSadiq - 更新你的问题 - 这不是你要问的"i just need the user to save to database"
  • 确定我希望将用户(newPay)保存在自己的数组中,如果我最初的问题不清楚,我很抱歉,我对此还是有点陌生​​
猜你喜欢
  • 2018-03-23
  • 2021-09-20
  • 2020-07-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-05
  • 2021-09-19
  • 2016-12-10
相关资源
最近更新 更多