Home > other >  Query was already executed, MoongoseError
Query was already executed, MoongoseError

Time:01-19

I am making a transaction controller in NodeJS but when I send data through postman I get this error:

MongooseError: Query was already executed: Customer.updateOne({ name: 'Axel' }, { '$set': { balance: 98...
    at model.Query._wrappedThunk [as _updateOne] (C:\Users\m4afy\Desktop\the spark foundation\Banking system\node_modules\mongoose\lib\helpers\query\wrapThunk.js:23:19)
    at C:\Users\m4afy\Desktop\the spark foundation\Banking system\node_modules\kareem\index.js:494:25
    at process.processTicksAndRejections (node:internal/process/task_queues:77:11) {
  originalStack: 'Error\n'  
    '    at model.Query._wrappedThunk [as _updateOne] (C:\\Users\\m4afy\\Desktop\\the spark foundation\\Banking system\\node_modules\\mongoose\\lib\\helpers\\query\\wrapThunk.js:27:28)\n'  
    '    at C:\\Users\\m4afy\\Desktop\\the spark foundation\\Banking system\\node_modules\\kareem\\index.js:494:25\n'  
    '    at process.processTicksAndRejections (node:internal/process/task_queues:77:11)'
}

my Transaction code goes as follow:

const Transaction = require('../models/transaction')
const Customer = require('../models/customers')

const cashTransaction = async (req, res, next) => {
    const {from, to, amount} = req.body

    try {
        let sender = await Customer.findOne({'name' : `${from}`})
        let senderBalance = Number(sender.balance) - Number(amount)
        await Customer.updateOne({name : from}, {balance : senderBalance}, err =>{
            if (err){
                console.log(err)
                res.status(500).send('Could not update sender information')
            } else {
                console.log('Sender information updated');     
            }       
        })

        let receiver = await Customer.findOne({name : to})
        let receiverBalance = Number(receiver.balance)   Number(amount)
        await Customer.updateOne({name : to}, {balance : receiverBalance}, err =>{
            if (err){
                console.log(err);
                res.status(500).send('Could not update receive ver information')
            } else{
                console.log('receiver information updated');
            }
        })

        const transaction = new Transaction({
            from,
            to,
            amount        
        })
        await transaction.save()
        res.status(200).json({transaction : {transaction} , message : 'transaction saved'})
    } catch (error) {
        console.log(error);
        res.status(500).send('An Error occured');
    }
}   

how can I update it multiple times? It worked one time but then am getting this error, any help?

CodePudding user response:

Using await and a callback simultaneously will result in the query executing twice.

The Model.updateOne method returns a query object. Passing a callback function causes the query to be immediately executed and then the callback is called. Await will likewise cause the query to be executed, and will return the result.

When you use both at the same time, both try to execute the query, but a specific instance of a query can only be executed once, hence the error.

You might try using await inside of a try/catch instead of a callback.

Each call to updateOne instantiates a new query object, so you should be able to do both updates

  • Related