如何通过几次更新保存猫鼬模型

时间:2019-07-16 12:03:32

标签: javascript node.js mongoose

我正在创建一个API方法,用于处理从一个帐户到另一个帐户的资金转移。从过帐请求中,我获得转账的帐户ID,转账金额和参考(用于创建交易)。

这是我的模式,它使用嵌入式文档方法。

const AccountSchema = mongoose.Schema({
    name: {type: String, required: true},
    number: {type: Number, index: true, unique: true, required: true},
    type: {type: String, required: true},
    status: {type: String, required: true},
    balance: {type: Number, required: true},
    user: {type: String, required: true},
    transactions: [TransactionSchema]
}, {
    timestamps: true
});
  • 首先,我想找到两个帐户“ from_account”和“ to_account”并存储它们的ID。
  • 接下来,我为帐户“ from_transaction”和“ to_transaction”创建交易对象。
  • 接下来,我将交易对象推入每个帐户的帐户数组中的交易字段。
  • 接下来,我使用每个交易金额的新余额更新帐户的新余额。
  • 接下来我保存。

当我完成所有这些操作后,除了可以保存使应用程序崩溃的其他功能外,它都可以正常工作。

我在做错什么,这甚至是正确的方法吗?

这是我的代码。 PS:我多次调用保存,这是错误的,但是一次调用也会产生错误,并说accounts.save()不是函数。我还要分别处理每个帐户,因为每个帐户都需要进行不同的处理。

exports.interAccountTransfer = (req, res) => {

    const logged_in_user = req.decoded;
    const { from_account, to_account, transfer_amount, from_ref, to_ref } = req.body;

    var from_transaction = new Transaction({
        name: 'INT.D',
        amount: -transfer_amount,
        reference: from_ref,
        type: 'debit'
    });

    var to_transaction = new Transaction({
        name: 'INT.C',
        amount: transfer_amount,
        reference: to_ref,
        type: 'credit'
    }); 

    Account.find({_id: {$in: [from_account, to_account] }, user: logged_in_user.user_id }, (err, accounts) => {

        if (!accounts) return res.status(404).send({ message: `Accounts not found!` });
        if (err) return res.status(500).send({ message: `Opps something went wrong!` });

        accounts[0].transactions.push(from_transaction);
        accounts[1].transactions.push(to_transaction);

        accounts[0].balance = accounts[0].balance - transfer_amount;
        accounts[1].balance = accounts[1].balance + parseInt(transfer_amount);


        accounts[0].save((err) => {
            if (err) {
                return res.status(500).send({ message: `Opps something went wrong!` });
            }

            res.status(200).send({ message: `Transaction added successfully!` });
        });

        accounts[1].save((err) => {
            if (err) {
                return res.status(500).send({ message: `Opps something went wrong!` });
            }

            res.status(200).send({ message: `Transaction added successfully!` });
        });

        res.send(accounts);  

    });

}

我想用新的余额和交易对象更新数组中的两个帐户。

2 个答案:

答案 0 :(得分:0)

您每次保存后写了两次

   res.status(200).send({ message: `Transaction added successfully!` });

保存两个文件后就可以发送文件

   accounts[0].save((err) => {
        if (err) {
            return res.status(500).send({ message: `Opps something went wrong!` 
            });
        }    
    });

    accounts[1].save((err) => {
        if (err) {
            return res.status(500).send({ message: `Opps something went wrong!` 
            });
        }            
    });

    res.status(200).send({ message: `Transaction added successfully!`,
                          accounts: accounts });

答案 1 :(得分:0)

您的代码中存在一些问题:

1。.find()方法始终返回一个数组,即使找不到匹配项,它仍然返回一个空数组,因此!accounts将始终为false

2。您不能确保accounts[0]来自帐户,accounts[1]来自帐户。

3。您在每次保存后发送响应。这会导致崩溃。

您可以通过使用两个查询来解决这些问题,一个查询来自帐户,一个查询至帐户,使用async/awaittry/catch避免回调地狱,并在一切完成后发送成功响应。

exports.interAccountTransfer = async (req, res) => {
  try {
    const logged_in_user = req.decoded;
    const { from_account, to_account, transfer_amount, from_ref, to_ref } = req.body;

    var from_transaction = new Transaction({
      name: 'INT.D',
      amount: -transfer_amount,
      reference: from_ref,
      type: 'debit'
    });

    var to_transaction = new Transaction({
      name: 'INT.C',
      amount: transfer_amount,
      reference: to_ref,
      type: 'credit'
    }); 

    var from = await Account.findOne({_id: from_account , user: logged_in_user.user_id });
    if (!from) return res.status(404).send({ message: `Accounts not found!` });
    var to = await Account.findOne({_id: to_account , user: logged_in_user.user_id });
    if (!to) return res.status(404).send({ message: `Accounts not found!` });

    from.transactions.push(from_transaction);
    to.transactions.push(to_transaction);

    from.balance = from.balance - transfer_amount;
    to.balance = to.balance + parseInt(transfer_amount);

    await from.save();
    await to.save();

    res.status(200).send({ message: `Transaction added successfully!` });
  } catch(err) {
    res.status(500).send({ message: `Opps something went wrong!` });
  }
}