You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

POST API关联Transaction与Wallet表更新Amount字段报错求助

Fixing Your Transaction-to-Wallet Update Flow & findAll Error

Let’s walk through what’s going wrong and fix this step by step—you’re almost there!

First: The Cannot read property 'findAll' of undefined Error

This is a super common gotcha—it means your authservice.js file doesn’t have access to your Wallet model. You’re trying to run wallet.findAll() but never told the file what wallet actually refers to. That’s an easy fix!

Second: Linking Transactions & Wallets

You’re on the right track using cardnum (from Transaction) to match cid (from Wallet), but there are a few logic gaps and undefined variables messing things up (like User.id and orders which don’t exist in your code).


Step 1: Fix Model Imports

First, add the Wallet model import to authservice.js (adjust the path to match where your models live):

const Wallet = require('../models/Wallet'); // Add this at the top

And make sure you’re importing the Transaction model in controller.js too—you’ll need it to create records.

Step 2: Rewrite the Controller Logic

Your controller has some undefined variables and mixed-up save calls. Here’s the cleaned-up version that properly links Transaction to Wallet:

const to = require('../utils/to'); // Assume this is your async error handler
const ReE = require('../utils/ReE');
const ReS = require('../utils/ReS');
const Transaction = require('../models/Transaction');
const AuthService = require('./authservice');

const create = async function(req, res){
    res.setHeader('Content-Type', 'application/json');
    let err, trans, wallet;
    const transaction_info = req.body;

    // 1. Create the Transaction record first
    [err, trans] = await to(Transaction.create(transaction_info));
    if(err){
        return ReE(res, err);
    }

    // 2. If amount is present, update the linked Wallet
    if ('amount' in transaction_info) {
        const walletUpdateData = {
            cid: transaction_info.cardnum, // Link using the cardnum from Transaction
            amount: transaction_info.amount,
            status: transaction_info.status
        };
        wallet = await AuthService.update(walletUpdateData);
        console.log('wallet_info : <<<<<<< ' + JSON.stringify(wallet));
        
        // Save the cardnum link to the Transaction (optional but useful for future queries)
        trans.cardnum = transaction_info.cardnum;
        await trans.save();
    }

    // Return the final Transaction data
    const transaction_json = trans.toWeb();
    return ReS(res, {trans: transaction_json}, 201);
}

module.exports.create = create;

Step 3: Fix the AuthService Update Logic

Your update function had a few bugs (like using transaction instead of order for sorting, and assigning User.id incorrectly). Here’s the corrected version that either updates an existing Wallet or creates a new one:

const to = require('../utils/to');
const TE = require('../utils/TE');
const Wallet = require('../models/Wallet'); // Critical import!

const update = async function (body) {
    let err, existingWallet, updatedWallet;
    const wallet_inf = body;

    // Find the latest Wallet record for the given cid
    [err, existingWallet] = await to(Wallet.findAll({
        limit: 1,
        where: { cid: wallet_inf.cid }, // Match the cid from the request
        order: [['id', 'DESC']] // Fix: Use 'order' instead of 'transaction' for sorting
    }));
    if(err) return TE(JSON.stringify(err));

    if(wallet_inf.status === true){
        if(existingWallet.length > 0){
            // If Wallet exists, update the amount (I used addition here—adjust to your needs!)
            const newAmount = existingWallet[0].amount + wallet_inf.amount;
            [err, updatedWallet] = await to(existingWallet[0].update({amount: newAmount}));
        } else {
            // If no Wallet exists, create a new one
            [err, updatedWallet] = await to(Wallet.create(wallet_inf));
        }
        if(err) return TE(JSON.stringify(err));
    } else {
        TE('Please check your balance');
    }

    return updatedWallet;
}

module.exports.update = update;

Extra Tips for Better Relationships

If you want to make this even cleaner, define a formal relationship between your Transaction and Wallet models using Sequelize:

// In your Transaction model
Transaction.belongsTo(Wallet, { foreignKey: 'cardnum', targetKey: 'cid' });

// In your Wallet model
Wallet.hasMany(Transaction, { foreignKey: 'cardnum', sourceKey: 'cid' });

This lets you easily fetch related Wallet data when querying Transactions (and vice versa) without manual matching.

内容的提问来源于stack exchange,提问作者Dinesh Kumar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 09:05:38