How can I get the List of Debit or Credit transactions Only. Like I have a column in my database , 2 columns actually.
I want to be able to query for Debit transactions or Credit , The endpoint is written in Node.Js and the backend is MongoDB
Suppose I am using MySQL (Just for you to understand , although i am using MongoDB ) I can run something like this
Select email, narration, credit , amount from narration where email = '[email protected]'
in MongoDB it is quite different. Please see the source code below, for a REST api
router.get("/get-credit-transaction/:email", async (req, res) => {
try {
if (
!req.headers.authorization ||
!req.headers.authorization.startsWith("Bearer ") ||
!req.headers.authorization.split(" ")[1]
) {
return res.status(422).json({ message: "Please Provide Token!" });
}
const trans = await Transaction.find(
{ email: req.params.email },
{ email: true, narration: true, credit: true, amount: true }
);
res.status(200).json(trans);
} catch (error) {
res.status(404).json({ message: error.message });
}
});
The same goes for Debit transactions
router.get("/get-debit-transaction/:email", async (req, res) => {
try {
if (
!req.headers.authorization ||
!req.headers.authorization.startsWith("Bearer ") ||
!req.headers.authorization.split(" ")[1]
) {
return res.status(422).json({ message: "Please Provide Token!" });
}
const trans = await Transaction.find(
{ email: req.params.email },
{ email: true, narration: true, debit: true, amount: true }
);
res.status(200).json(trans);
} catch (error) {
res.status(404).json({ message: error.message });
}
});
Saving the transaction done, I do it like so
const transactions = new Trans({
email: email,
narration: narration,
credit: 0.0,
debit: amount,
amount: amount,
});
try {
transactions.save();
//res.send(savedUser);
console.log("transaction saved");
} catch (err) {
//res.status(400).send(err);
console.log(err);
}
the above code is to save Debit transactions. Now back to the question, how do I get the list of transactions , be it Debit or Credit using Node.JS and the backend is MongoDB?
2
Answers
Ideally, you should have a separate column, let’s say
transactionType
denoting the type of the transactionCredit
orDebit
. In the current case, to search for debit transactions, you can apply a filterwhere credit = 0.0
or vice-versa. Like this:To shorten the code and get back the desired result. It will result for both debit and credit. Send type query param as
type=credit
ortype=debit
as shown in the following URL.