I am fairly new to Coding and JavaScript altogether. I am trying to render the Data inside stored inside my MongoDB in my EJS template.
The specific code is here in app.js
// Individual Customer's page
app.get("/customers/all-customers/:customerPhoneNumber", function (req, res) {
const requestedCustomerPhoneNumber = req.params.customerPhoneNumber;
Customer.findOne({ phone: requestedCustomerPhoneNumber }, function (
err,
foundCustomer
) {
Purchase.find({ customerPhone: requestedCustomerPhoneNumber }, function (
err,
foundPurchases
) {
// console.log(foundPurchases);
foundPurchases.forEach(function (purchase) {
const planPurchaseID = purchase.purchaseID;
CompletedSession.findOne({ planPurchaseID: planPurchaseID }, function (err, foundSession) {
res.render("customer-page", {
customerPurchases: foundPurchases,
pageTitle: foundCustomer.name,
customerID: foundCustomer._id,
customerPhone: foundCustomer.phone,
customerWhatsapp: foundCustomer.whatsappNumber,
customerEmail: foundCustomer.email,
customerDOB: foundCustomer.dob,
customerGender: foundCustomer.gender,
customerRegDate: foundCustomer.registrationDate,
comletedSessions: foundSession.sessions,
});
})
})
});
});
});
In this code, Some of the document has null
value of sessions
in foundSession
, which cause my program to crash when I try to render the array with forEach()
loop.
Is there any way to automatically drop foundSession
with null
value of sessions
so that I can only pass the foundSession
that has no null
value of sessions
and prevent my program from crashing?
You can add a
$ne
-condition to your query for filtering the sessions: