'Getting Null From MongoDB
Why my Code Giving me Null
async function run() {
try {
await client.connect();
const productsCollection = client.db("inventory").collection("items");
// Get All Products
app.get('/products', async (req, res) => {
const query = {};
const cursor = productsCollection.find(query);
const products = await cursor.toArray();
res.send(products);
});
// Get Single Product
app.get('/products/:id', async (req, res) => {
const id = req.params.id;
console.log(id);
const query = {_id: ObjectId(id)};
const product = await productsCollection.findOne(query);
res.send(product);
})
}
finally {
}
}
run().catch(console.dir);
I do not understand why Null is showing? And there is no error in giving products /id And It doesn't even showing anything And this error is showing in the front end console Uncaught (in promise) SyntaxError: Unexpected end of JSON input
Solution 1:[1]
In mongo, you should use await on every event that is related to the database. this is because it takes time to actually retrieve the data from the collection and the javascript code will not wait unless you tell it to.
in your example
const cursor = productsCollection.find(query);
should be
const cursor = await productsCollection.find(query);
this is my first note
My second note is to share your frontend code and I will edit the answer if there is any thing to add
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ahmed Gaafer |
