node.jsexpresspostmanhttp-status-code-500

Getting error 500 on DELETE request in Postman


I am following a node.js & express api tutorial to build an expense tracker. I am making get, post and delete requests on postman. The GET and POST request are working fine but i get status as 500 when i make a DELETE request. Consider the following:

POST: http://localhost:5000/api/v1/transactions

Output:

{
    "success": true,
    "data": {
        "text": "Payment",
        "amount": -100,
        "_id": "6662fcccc69f5411146a4205",
        "createdAt": "2024-06-07T12:27:56.355Z",
        "__v": 0
    }
}

GET: http://localhost:5000/api/v1/transactions

Output:

{
    "success": true,
    "count": 3,
    "data": [
        {
            "_id": "6662f5b0432dc072d8281525",
            "text": "Bonus",
            "amount": 50,
            "createdAt": "2024-06-07T11:57:36.455Z",
            "__v": 0
        },
        {
            "_id": "6662f654432dc072d8281528",
            "text": "Books",
            "amount": 150,
            "createdAt": "2024-06-07T12:00:20.681Z",
            "__v": 0
        },
        {
            "_id": "6662fcccc69f5411146a4205",
            "text": "Payment",
            "amount": -100,
            "createdAt": "2024-06-07T12:27:56.355Z",
            "__v": 0
        }
    ]
}

Note: I earlier added **Bonus** and **Books**

DELETE: say i want to delete 'Payment', so i get its _id and do: http://localhost:5000/api/v1/transactions/6662fcccc69f5411146a4205

Output:

{
    "success": false,
    "error": "Server Error"
}

The controllers file (transactions.js) is as follows:

const Transaction = require('../models/Transaction');

// @desc    Get all transactions
// @route   GET /api/vi/transactions 
// @access  Public
exports.getTransactions = async (req, res, next) => {
    // res.send('GET transactions');
    try {
        const transactions = await Transaction.find();

        return res.status(200).json({
            success: true,
            count: transactions.length,
            data: transactions
        });
    } catch (err) {
        return res.status(500).json({
            success: false,
            error: 'Server Error'
        });
    }
}


// @desc    Add transaction
// @route   POST /api/vi/transactions 
// @access  Public
exports.addTransaction = async (req, res, next) => {
    // res.send('POST transaction');

    try {
        const { text, amount } = req.body;

        const transaction = await Transaction.create(req.body);
    
        return res.status(201).json({
            success: true,
            data: transaction
        });
        
    } catch (err) {
        if (err.name === 'ValidationError') {
            const messages = Object.values(err.errors).map(val => val.message);

            return res.status(400).json({
                success: false,
                error: messages
            });
        } else {
            return res.status(500).json({
                success: false,
                error: 'Server Error'
            });
        }
    }
}


// @desc    Delete transaction
// @route   DELETE /api/vi/transactions/:id
// @access  Public
exports.deleteTransaction = async (req, res, next) => {
    // res.send('DELETE transaction');
    try {
        const transaction = await Transaction.findById(req.params.id);

        if(!transaction) {
            return res.status(404).json({
                success: false,
                error: 'No transaction found'
            });
        }

        await transaction.remove(); //remove method is called on the resource

        return res.status(200).json({
            success: true,
            data: {}
        });

    } catch (err) {
        return res.status(500).json({
            success: false,
            error: 'Server Error'
        });
    }
}

Please somebody help. How do i solve this?


Solution

  • Upon doing console.log(err), I got TypeError: transaction.remove is not a function, i.e., it is deprecated. Instead, I used const transaction = await Transaction.findByIdAndDelete(req.params.id) which solved the problem. findByIdAndDelete finds and deletes the document, returning the deleted document. It returns the document that was deleted, or null if no document with the given _id exists.

    I commented out the await transaction.remove() because findByIdAndDelete does the job.

    There's an another way this can be solved: Keep findById unchanged, just do await transaction.deleteOne(). This also does the job.

    Anyway, this problem has been resolved. Thanks to @jQueeny!