Description:
I am working on a project where I fetch a list of universities based on their IDs from the database. Despite having the correct IDs and ensuring the data exists in the database, my query is returning an empty array. Here are the details of my setup and the steps I’ve taken to troubleshoot the issue.
Backend Code:
I have set up an Express route and corresponding controller to handle the request:
Route:
app.post('/shortlisted-universities', getAllShortlistedUniversities);
Controller:
async function getAllShortlistedUniversities(req, res) {
const { ids } = req.body;
if (!ids || !Array.isArray(ids) || ids.length === 0) {
return res.status(400).jsonp("Invalid university IDs provided!");
}
try {
const data = await findUniversityList(ids);
if (data && data.length > 0) {
return res.status(200).jsonp({ universities: data });
} else {
return res.status(404).jsonp("No universities found with the provided IDs!");
}
} catch (error) {
console.error(`Error fetching universities: ${error}`);
return res.status(500).send("Error getting university data.");
}
}
Service Function:
const { ObjectId } = require('mongodb');
async function findUniversityList(ids) {
try {
const objectIdArray = ids.map(id => ObjectId(id)); // Convert ids to ObjectId
const query = { _id: { $in: objectIdArray } };
console.log("Query:", query); // Log the query for inspection
// Log the collection name and ensure the connection is open
console.log("Collection Name:", universityModel.collection.name);
console.log("Database Name:", universityModel.db.name);
// Verify the connection state
console.log("Connection Ready State:", universityModel.db.readyState);
const data = await universityModel.find(query).sort({ updatedAt: -1 });
console.log('data after query', data);
return data;
} catch (e) {
console.error("Error in findUniversityList:", e);
throw e;
}
}
Logs:
Here are the logs that I receive from my service function:
Query: {
_id: {
'$in': [
new ObjectId("5f915d091577ad2b77b29459"),
new ObjectId("5f915d091577ad2b77b29458"),
new ObjectId("5f915d091577ad2b77b2945a"),
new ObjectId("5f915d091577ad2b77b2945b"),
new ObjectId("61a74808652ee9728527e8f7")
]
}
}
Collection Name: universities
Database Name: test
Connection Ready State: 1
data after query []
Troubleshooting Steps Taken:
-
Verified Data Existence: Manually checked that the data exists in the MongoDB collection
universities
within thetest
database. -
Checked Document Structure: Ensured that
_id
fields in my documents are stored asObjectId
. -
Schema Definition: Confirmed that the Mongoose schema and model match the structure of my MongoDB documents.
-
Verified Connection: Ensured that the MongoDB connection is correctly established and active.
What I’ve Tried:
-
Converting string IDs to
ObjectId
in the service function. -
Adding additional logging to validate the query and connection details.
What I’m Seeing:
Despite the query being well-formed and the IDs being correct, the query returns an empty array.
Request:
Can someone help me identify what might be going wrong? Any insights or suggestions would be greatly appreciated.
Engr Md Ferdous Alam is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.